Example #1
0
 /// <summary>
 ///     Creates a new <see cref="Population{TProgram,TOutput}" /> with the given arguments.
 /// </summary>
 /// <param name="maxSize">The maximum size of the population.</param>
 /// <param name="primitives">The primitive set used to generate new programs.</param>
 /// <param name="programGenerator">The generator of new programs.</param>
 /// <param name="programComparer">The function used to compare programs and select the best program.</param>
 /// <param name="selectionOperator">The operator to perform selection.</param>
 /// <param name="crossoverOperator">The operator to crossover programs. </param>
 /// <param name="mutationOperator">The operator to mutate programs.</param>
 /// <param name="maxGenerationDepth">The maximum depth of elements generated during GP.</param>
 /// <param name="maxElementLength">The maximum length of elements generated during GP.</param>
 /// <param name="crossoverPercent">The percentage of a population used for the crossover operator during GP.</param>
 /// <param name="mutationPercent">The percentage of a population used for the mutation operator during GP.</param>
 /// <param name="elitismPercent">The percentage of a population used for elite selection during GP.</param>
 public Population(
     uint maxSize,
     PrimitiveSet <TProgram> primitives,
     IProgramGenerator <TProgram, TOutput> programGenerator,
     IComparer <TProgram> programComparer,
     ISelectionOperator <TProgram> selectionOperator,
     ICrossoverOperator <TProgram> crossoverOperator,
     IMutationOperator <TProgram> mutationOperator,
     uint maxGenerationDepth = 4,
     uint maxElementLength   = 20,
     double crossoverPercent = 0.65d,
     double mutationPercent  = 0.2d,
     double elitismPercent   = 0.1d)
 {
     this._maxSize            = maxSize;
     this._primitives         = primitives;
     this._programGenerator   = programGenerator;
     this._maxGenerationDepth = maxGenerationDepth;
     this._maxElementLength   = maxElementLength;
     this._programComparer    = programComparer;
     this._selectionOperator  = selectionOperator;
     this._mutationOperator   = mutationOperator;
     this._crossoverOperator  = crossoverOperator;
     this.ElitismPercent      = elitismPercent;
     this.MutationPercent     = mutationPercent;
     this.CrossoverPercent    = crossoverPercent;
 }
        private TProgram Generate(PrimitiveSet <TProgram> primitives, uint depth, uint maxDepth)
        {
            // check max depth, just return a random terminal program
            if (depth == maxDepth)
            {
                return(primitives.Terminals.ToList().GetRandomItem(this._random));
            }

            // otherwise, get a random primitive
            var primitivesList = primitives.Functions.ToList();

            primitivesList.AddRange(primitives.Terminals);
            var program = primitivesList.GetRandomItem(this._random);

            // recursively generate random children for it
            var numChildren = program.Children.Count;
            var children    = new ITreeProgram <TOutput> [numChildren];

            for (var i = 0; i < numChildren; i++)
            {
                children[i] = this.Generate(primitives, depth + 1, maxDepth);
            }

            // generate a new program with the children
            return((TProgram)program.CreateNew(children));
        }
Example #3
0
 /// <summary>
 ///     Creates anew <see cref="SubtreeMutation{TProgram,TOutput}" /> with the given arguments.
 /// </summary>
 /// <param name="programGenerator">The generator for new sub-programs. </param>
 /// <param name="primitives">The primitive set to be used in mutation operations.</param>
 /// <param name="maxDepth">The maximum depth of new random sub-programs.</param>
 public SubtreeMutation(
     IProgramGenerator <TProgram, TOutput> programGenerator, PrimitiveSet <TProgram> primitives,
     uint maxDepth)
 {
     this._primitives       = primitives;
     this._programGenerator = programGenerator;
     this.MaxDepth          = maxDepth;
 }
Example #4
0
        private static MathExpressionConverter GetConverter(out Variable varX, out Variable varY)
        {
            varX = new Variable("x", 2, new Range(-1, 1));
            varY = new Variable("y", new Range(1, 4));
            var primitiveSet = new PrimitiveSet <MathProgram>(new List <Terminal> {
                varX, varY
            }, new MathProgram[0]);

            primitiveSet.Add(MathPrimitiveSets.Default);
            return(new MathExpressionConverter(primitiveSet));
        }
Example #5
0
        public void RestrictedGenerationTest()
        {
            var generator    = new FullProgramGenerator <MathProgram, double>();
            var primitiveSet =
                new PrimitiveSet <MathProgram>(new[] { Constant.Zero }, new[] { new CosineFunction(Constant.Zero) });
            var prog = generator.Generate(primitiveSet, 1);

            Console.WriteLine(prog);
            Assert.AreEqual(prog, primitiveSet.Functions.First(),
                            $"The only program to be generated should be {primitiveSet.Functions.First()}.");
        }
Example #6
0
        private static MathExpressionConverter GetConverter()
        {
            var varX         = new Variable("x");
            var varY         = new Variable("y");
            var varZ         = new Variable("z");
            var primitiveSet = new PrimitiveSet <MathProgram>(
                new List <Terminal> {
                varX, varY, varZ
            }, MathPrimitiveSets.Default.Functions);

            return(new MathExpressionConverter(primitiveSet));
        }
Example #7
0
        private static MathExpressionConverter GetConverter(out Variable xVar, out Variable yVar)
        {
            xVar = new Variable("x", new Range(-1, 1));
            yVar = new Variable("y", new Range(2, 4));
            var primitiveSet = new PrimitiveSet <MathProgram>(
                new List <Terminal> {
                xVar, yVar
            }, new MathProgram[0]);

            primitiveSet.Add(MathPrimitiveSets.Default);
            var converter = new MathExpressionConverter(primitiveSet);

            return(converter);
        }
Example #8
0
 /// <summary>
 ///  Will synk the state of the given PrimitiveSet with this ObjectSets state
 /// </summary>
 /// <param name="primitiveGrid"></param>
 public void synkPrimitiveSet(PrimitiveSet primitiveGrid)
 {
     if (primitiveGrid != null)
     {
         resizePrimitiveIDs(primitiveGrid);
         if (enemySet != null)
         {
             for (int loopRow = 0; loopRow < enemySet.Length; loopRow++)
             {
                 if (enemySet[loopRow] != null)
                 {
                     for (int loopCollumn = 0; loopCollumn < enemySet[loopRow].Length; loopCollumn++)
                     {
                         primitiveGrid.getIDArray()[loopRow][loopCollumn] = -1;
                         if (enemySet[loopRow][loopCollumn] != null)
                         {
                             if (enemySet[loopRow][loopCollumn].ID <= 0)
                             {
                                 enemySet[loopRow][loopCollumn].ID = primitiveGrid.getUniqueID();
                             }
                             primitiveGrid.getIDArray()[loopRow][loopCollumn] = enemySet[loopRow][loopCollumn].ID;
                         }
                     }
                 }
             }
             primitiveGrid.resizeArrays();
             for (int loopRow = 0; loopRow < enemySet.Length; loopRow++)
             {
                 if (enemySet[loopRow] != null)
                 {
                     for (int loopCollumn = 0; loopCollumn < enemySet[loopRow].Length; loopCollumn++)
                     {
                         if (enemySet[loopRow][loopCollumn] != null)
                         {
                             primitiveGrid.getTypeArray()[loopRow][loopCollumn]            = (int)enemySet[loopRow][loopCollumn].getType();
                             primitiveGrid.getHealthIncrementArray()[loopRow][loopCollumn] = enemySet[loopRow][loopCollumn].getMaximumHealth();
                             //if((int)(primitiveGrid.getHealthArray()[loopRow][loopCollumn] * (float)enemySet[loopRow][loopCollumn].getMaximumHealth()) != enemySet[loopRow][loopCollumn].getHealth()){
                             primitiveGrid.getHealthArray()[loopRow][loopCollumn] = ((float)enemySet[loopRow][loopCollumn].getHealth() / (float)enemySet[loopRow][loopCollumn].getMaximumHealth());
                             //}
                             primitiveGrid.getScoreArray()[loopRow][loopCollumn]    = enemySet[loopRow][loopCollumn].getScore();
                             primitiveGrid.getRevealedArray()[loopRow][loopCollumn] = enemySet[loopRow][loopCollumn].isRevealed();
                         }
                     }
                 }
             }
         }
     }
 }
Example #9
0
        public MainForm()
        {
            this.InitializeComponent();

            // creates primitives
            var terminals = new List <MathProgram>();

            for (var c = 'a'; c <= 'z'; c++)
            {
                terminals.Add(new Variable(c.ToString()));
            }
            var primitives = new PrimitiveSet <MathProgram>(terminals, MathPrimitiveSets.Default.Functions);

            // creates converter
            this._converter = new MathExpressionConverter(primitives);
        }
Example #10
0
        /// <summary>
        ///     Creates a new <see cref="PointMutation{TProgram,TOutput}" /> with the given mutation probability and primitive set.
        /// </summary>
        /// <param name="primitives">The primitive set to be used in mutation operations.</param>
        /// <param name="mutationProbability">The probability of mutating each sub-program.</param>
        public PointMutation(PrimitiveSet <TProgram> primitives, double mutationProbability = 0.5d)
        {
            // stores primitives as a function of their arity (0, 1, ...)
            var allPrimitives = new List <TProgram>(primitives.Functions);

            allPrimitives.AddRange(primitives.Terminals);
            foreach (var primitive in allPrimitives)
            {
                var arity = primitive.Children.Count;
                if (!this._primitives.ContainsKey(arity))
                {
                    this._primitives.Add(arity, new List <TProgram>());
                }
                this._primitives[arity].Add(primitive);
            }

            this.MutationProbability = mutationProbability;
        }
Example #11
0
        private static Population <MathProgram, double> CreatePopulation()
        {
            var consts = new HashSet <Terminal>();

            for (var i = 0; i < MAX_SIZE; i++)
            {
                consts.Add(new Constant(i));
            }

            var primitives      = new PrimitiveSet <MathProgram>(consts, new HashSet <MathProgram>());
            var fullGen         = new FullProgramGenerator <MathProgram, double>();
            var fitnessFunction = new FitnessFunction();
            var pop             = new Population <MathProgram, double>(
                MAX_SIZE, primitives, fullGen, fitnessFunction, null, null, null, 0);

            pop.Init(new HashSet <MathProgram>());
            return(pop);
        }
Example #12
0
        private static Population <MathProgram, double> CreatePopulation()
        {
            var consts = new HashSet <Terminal>();

            for (var i = 0; i < MAX_SIZE; i++)
            {
                consts.Add(new Constant(i));
            }

            var primitives      = new PrimitiveSet <MathProgram>(consts, new HashSet <MathProgram>());
            var fullGen         = new FullProgramGenerator <MathProgram, double>();
            var fitnessFunction = new FitnessFunction();
            var pop             = new Population <MathProgram, double>(
                MAX_SIZE, primitives, fullGen, fitnessFunction,
                new TournamentSelection <MathProgram>(fitnessFunction, 5),
                new OnePointCrossover <MathProgram, double>(),
                new SimplifyMutation(), 0, 20, 0.65, 0.2, 0.1);

            pop.Init(new HashSet <MathProgram>());
            return(pop);
        }
Example #13
0
        private static MathProgram CreateProgram()
        {
            var a        = new Variable("a");
            var b        = new Variable("b");
            var c        = new Variable("c");
            var d        = new Variable("d");
            var e        = new Variable("e");
            var addition = new AdditionFunction(a, a);
            var subtr    = new SubtractionFunction(a, a);

            var primitives = new PrimitiveSet <MathProgram>(
                new HashSet <Terminal> {
                a, b, c, d, e
            },
                new HashSet <MathProgram> {
                addition, subtr
            });

            var converter = new MathExpressionConverter(primitives);

            return(converter.FromPrefixNotation("(+ (- a b) (- c (+ d e)))"));
        }
Example #14
0
 /// <summary>
 /// Will Find and return the column positions of the enemies affected by the light
 /// </summary>
 /// <param name="targetSet">the set of Enemies this Light will find targets in. Note if no IDArray was set this set cannot target any enemies </param>
 /// <returns>the array is organized as a 1D array[Number of Enemies Found] where array[?] = the column where an enemy was found.
 ///  Note: there is one entry per enemy found. So duplicate column entries indicate more than one enemy is targeted in the column in question</returns>
 public int[] getTargetedEnemyColumns(PrimitiveSet targetSet)
 {
     if (targetSet != null && targetSet.getIDArray() != null)
     {
         //Laser
         if (type == lightType.LASER)
         {
             return(getTargetedEnemyLocations1DLASER(targetSet.getIDArray(), currentPosition));
         }
         //Wide
         else if (type == lightType.WIDE)
         {
             return(getTargetedEnemyLocations1DWIDE(targetSet.getIDArray(), currentPosition));
         }
         //Mid
         else
         {
             return(getTargetedEnemyLocations1DMEDIUM(targetSet.getIDArray(), currentPosition));
         }
     }
     return(null);
 }
Example #15
0
 /// <inheritdoc />
 public TProgram Generate(PrimitiveSet <TProgram> primitives, uint maxDepth) =>
 this._possibleGenerators.GetRandomItem(this._random).Generate(primitives, maxDepth);
Example #16
0
 /// <inheritdoc />
 public TProgram Generate(PrimitiveSet <TProgram> primitives, uint maxDepth)
 {
     return(this.Generate(primitives, 0, maxDepth));
 }
Example #17
0
        public static void Main(string[] args)
        {
            const uint   popSize          = 200;
            const uint   maxDepth         = 4;
            const uint   maxGenerations   = 2000;
            const uint   maxElementLength = 20;
            const uint   maxNoImproveGen  = (uint)(maxGenerations * 0.5);
            const string solutionExp      = "(+ (+ x x) (+ (* 3 (* x x)) 1))";

            var variable = new Variable("x");

            var primitives = new PrimitiveSet <MathProgram>(
                new HashSet <Terminal> {
                variable, new Constant(0), new Constant(1), new Constant(3)
            },
                new HashSet <MathProgram>());

            primitives.Add(MathPrimitiveSets.Default);

            var fitnessFunction = new FitnessFunction(x => 2 * x + 3 * x * x + 1, variable, 100, -50, 50);

            var solution = new MathExpressionConverter(primitives).FromPrefixNotation(solutionExp);

            Console.WriteLine("===================================");
            Console.WriteLine("Fitness: {0} | {1}", fitnessFunction.Evaluate(solution), solution);
            solution.ToGraphvizFile(Path.GetFullPath("."), "solution", GraphvizImageType.Png);
            Console.WriteLine("===================================");

            var seed = new AdditionFunction(new Constant(1), variable);

            var elementGenerator =
                new StochasticProgramGenerator <MathProgram, double>(
                    new List <IProgramGenerator <MathProgram, double> >
            {
                new GrowProgramGenerator <MathProgram, double>(),
                new FullProgramGenerator <MathProgram, double>()
            });
            var selection = new TournamentSelection <MathProgram>(fitnessFunction, (uint)(popSize * 0.05));
            var crossover = new StochasticCrossover <MathProgram>(
                new List <ICrossoverOperator <MathProgram> >
            {
                new SubtreeCrossover <MathProgram, double>(),
                new OnePointCrossover <MathProgram, double>(),
                new ContextPreservingCrossover <MathProgram, double>(),
                new UniformCrossover <MathProgram, double>()
            });
            var mutation = new StochasticMutation <MathProgram>(
                new List <IMutationOperator <MathProgram> >
            {
                new SubtreeMutation <MathProgram, double>(elementGenerator, primitives, 1),
                new PointMutation <MathProgram, double>(primitives),

                //new ShrinkMutation(primitives),
                new SimplifyMutation(),
                new HoistMutation <MathProgram, double>()
            });

            var pop = new Population <MathProgram, double>(
                popSize, primitives, elementGenerator,
                fitnessFunction, selection, crossover, mutation, maxDepth, maxElementLength);

            pop.Init(new HashSet <MathProgram> {
                seed
            });

            MathProgram best             = null;
            var         numNoImproveGens = -1;

            for (var i = 0u; i < maxGenerations && numNoImproveGens < maxNoImproveGen; i++)
            {
                pop.Step();

                var newBest = pop.BestProgram;
                if (best == null)
                {
                    best = newBest;
                }
                var diff = fitnessFunction.Evaluate(newBest) - fitnessFunction.Evaluate(best);
                numNoImproveGens = diff.Equals(0) && best.Equals(newBest) ? numNoImproveGens + 1 : 0;
                best             = newBest;

                Print(pop, i, fitnessFunction, diff);
            }

            best.ToGraphvizFile(Path.GetFullPath("."), "best", GraphvizImageType.Png);
            Console.WriteLine("===================================");
            Console.WriteLine($"Best: {pop.BestProgram}, fitness: {fitnessFunction.Evaluate(pop.BestProgram):0.000}");
            Console.ReadKey();
        }
Example #18
0
 /// <summary>
 /// Will resize the idArray in the given PrimitiveSet and will
 /// </summary>
 /// <param name="primitiveGrid"></param>
 private void resizePrimitiveIDs(PrimitiveSet primitiveGrid)
 {
     if (primitiveGrid != null && enemySet != null)
     {
         //Rows
         //Create
         if (primitiveGrid.getIDArray() == null)
         {
             int[][] newIDArray = new int[enemySet.Length][];
             for (int loopRow = 0; loopRow < enemySet.Length; loopRow++)
             {
                 newIDArray[loopRow] = null;
             }
             primitiveGrid.setIDArray(newIDArray);
         }
         //Resize
         else if (primitiveGrid.getIDArray().Length < enemySet.Length)
         {
             int[][] newIDArray = new int[enemySet.Length][];
             int     loop       = 0;
             while (loop < primitiveGrid.getIDArray().Length)
             {
                 newIDArray[loop] = primitiveGrid.getIDArray()[loop];
                 loop++;
             }
             while (loop < newIDArray.Length)
             {
                 newIDArray[loop] = null;
                 loop++;
             }
             primitiveGrid.setIDArray(newIDArray);
         }
         //Columns
         for (int loopRow = 0; loopRow < enemySet.Length; loopRow++)
         {
             if (enemySet[loopRow] != null)
             {
                 //Create
                 if (primitiveGrid.getIDArray()[loopRow] == null)
                 {
                     int[] newIDArray = new int[enemySet[loopRow].Length];
                     for (int loopCollumn = 0; loopCollumn < newIDArray.Length; loopCollumn++)
                     {
                         newIDArray[loopCollumn] = 0;
                     }
                     primitiveGrid.getIDArray()[loopRow] = newIDArray;
                 }
                 //Resize
                 else if (primitiveGrid.getIDArray()[loopRow].Length < enemySet[loopRow].Length)
                 {
                     int[] newIDArray  = new int[enemySet[loopRow].Length];
                     int   loopCollumn = 0;
                     while (loopCollumn < primitiveGrid.getIDArray()[loopRow].Length)
                     {
                         newIDArray[loopCollumn] = primitiveGrid.getIDArray()[loopRow][loopCollumn];
                         loopCollumn++;
                     }
                     while (loopCollumn < newIDArray.Length)
                     {
                         newIDArray[loopCollumn] = 0;
                         loopCollumn++;
                     }
                     primitiveGrid.getIDArray()[loopRow] = newIDArray;
                 }
             }
         }
     }
 }
Example #19
0
            public SeparateDataShape(EndianBinaryReader er)
            {
                Type = er.ReadUInt32();
                Signature = er.ReadString(Encoding.ASCII, 4);
                if (Signature != "SOBJ") throw new SignatureNotCorrectException(Signature, "SOBJ", er.BaseStream.Position);
                Revision = er.ReadUInt32();
                NameOffset = (UInt32)er.BaseStream.Position + er.ReadUInt32();
                Unknown2 = er.ReadUInt32();
                Unknown3 = er.ReadUInt32();
                Flags = (ShapeFlags)er.ReadUInt32();
                OrientedBoundingBoxOffset = (UInt32)er.BaseStream.Position + er.ReadUInt32();
                PositionOffset = er.ReadVector3();
                NrPrimitiveSets = er.ReadUInt32();
                PrimitiveSetOffsetsArrayOffset = (UInt32)er.BaseStream.Position + er.ReadUInt32();
                BaseAddress = er.ReadUInt32();
                NrVertexAttributes = er.ReadUInt32();
                VertexAttributeOffsetsArrayOffset = (UInt32)er.BaseStream.Position + er.ReadUInt32();
                BlendShapeOffset = er.ReadUInt32();
                if (BlendShapeOffset != 0) BlendShapeOffset += (UInt32)er.BaseStream.Position - 4;

                long curpos = er.BaseStream.Position;
                er.BaseStream.Position = NameOffset;
                Name = er.ReadStringNT(Encoding.ASCII);
                er.BaseStream.Position = OrientedBoundingBoxOffset;
                BoundingBox = BoundingVolume.FromStream(er);

                er.BaseStream.Position = PrimitiveSetOffsetsArrayOffset;
                PrimitiveSetOffsets = new uint[NrPrimitiveSets];
                for (int i = 0; i < NrPrimitiveSets; i++)
                {
                    PrimitiveSetOffsets[i] = (UInt32)er.BaseStream.Position + er.ReadUInt32();
                }

                er.BaseStream.Position = VertexAttributeOffsetsArrayOffset;
                VertexAttributeOffsets = new uint[NrVertexAttributes];
                for (int i = 0; i < NrVertexAttributes; i++)
                {
                    VertexAttributeOffsets[i] = (UInt32)er.BaseStream.Position + er.ReadUInt32();
                }

                PrimitiveSets = new PrimitiveSet[NrPrimitiveSets];
                for (int i = 0; i < NrPrimitiveSets; i++)
                {
                    er.BaseStream.Position = PrimitiveSetOffsets[i];
                    PrimitiveSets[i] = new PrimitiveSet(er);
                }

                VertexAttributes = new VertexAttributeCtr[NrVertexAttributes];
                if (NrVertexAttributes != 0)
                {
                    for (int i = 0; i < NrVertexAttributes; i++)
                    {
                        er.BaseStream.Position = VertexAttributeOffsets[i];
                        VertexAttributes[i] = VertexAttributeCtr.FromStream(er);
                    }
                }

                if (BlendShapeOffset != 0)
                {
                    er.BaseStream.Position = BlendShapeOffset;
                    BlendShape = new BlendShapeCtr(er);
                }

                er.BaseStream.Position = curpos;
            }
Example #20
0
 /// <summary>
 ///     Creates a new <see cref="ShrinkMutation{TProgram,TOutput}" /> with the given primitives.
 /// </summary>
 /// <param name="primitives">The primitive set to be used in mutation operations.</param>
 public ShrinkMutation(PrimitiveSet <TProgram> primitives)
 {
     this._terminals = primitives.Terminals.ToList();
 }
Example #21
0
                public override void GetVertexData(Polygon Destination, PrimitiveSet PrimitiveSet, CMDL Model)
                {
                    var p = Destination;
                    int Vertices = (int)(VertexStreamLength / VertexDataEntrySize);
                    int Offset = 0;
                    byte[] VertexData = VertexStream;
                    foreach (var v in VertexStreams)
                    {
                        switch (v.Usage)
                        {
                            case VertexAttributeUsage.Position: p.Vertex = new Vector3[Vertices]; break;
                            case VertexAttributeUsage.Normal: p.Normals = new Vector3[Vertices]; break;
                            //case VertexAttributeUsage.Tangent: break;
                            case VertexAttributeUsage.Color: p.Colors = new Color[Vertices]; break;
                            case VertexAttributeUsage.TextureCoordinate0: p.TexCoords = new Vector2[Vertices]; break;
                            case VertexAttributeUsage.TextureCoordinate1: p.TexCoords2 = new Vector2[Vertices]; break;
                            case VertexAttributeUsage.TextureCoordinate2: p.TexCoords3 = new Vector2[Vertices]; break;
                            case VertexAttributeUsage.BoneIndex: break;
                            case VertexAttributeUsage.BoneWeight: break;
                            default:
                                break;
                        }
                    }
                    for (int i = 0; i < Vertices; i++)
                    {
                        byte[] bones = new byte[0];
                        foreach (var v in VertexStreams)
                        {
                            float[] Vars = new float[v.NrComponents];
                            int offs_ = 0;
                            for (int q = 0; q < v.NrComponents; q++)
                            {
                                switch (v.FormatType)
                                {
                                    case DataType.GL_BYTE:
                                        Vars[q] = (sbyte)VertexData[Offset + (int)v.Offset + offs_] * v.Scale;
                                        offs_++;
                                        break;
                                    case DataType.GL_UNSIGNED_BYTE:
                                        Vars[q] = VertexData[Offset + (int)v.Offset + offs_] * v.Scale;
                                        offs_++;
                                        break;
                                    case DataType.GL_SHORT:
                                        Vars[q] = IOUtil.ReadS16LE(VertexData, Offset + (int)v.Offset + offs_) * v.Scale;
                                        offs_ += 2;
                                        break;
                                    case DataType.GL_FLOAT:
                                        Vars[q] = BitConverter.ToSingle(VertexData, Offset + (int)v.Offset + offs_);
                                        offs_ += 4;
                                        break;
                                }
                            }
                            switch (v.Usage)
                            {
                                case VertexAttributeUsage.Position:
                                    p.Vertex[i] = new Vector3(Vars[0], Vars[1], Vars[2]);
                                    if (PrimitiveSet.RelatedBones != null && PrimitiveSet.RelatedBones.Length == 1) p.Vertex[i] = p.Vertex[i] * Model.Skeleton.GetMatrix((int)PrimitiveSet.RelatedBones[0]);//SkeletonCtr.TransformByMtx(p.Vertex[i], Model.Skeleton.GetMatrix((int)PrimitiveSet.RelatedBones[0]));
                                    break;
                                case VertexAttributeUsage.Normal:
                                    p.Normals[i] = new Vector3(Vars[0], Vars[1], Vars[2]);
                                    break;
                                case VertexAttributeUsage.Tangent:
                                    {
                                        Vector3 unk = new Vector3(Vars[0], Vars[1], Vars[2]);
                                    }
                                    break;
                                case VertexAttributeUsage.Color:
                                    if (Vars[0] < 0) Vars[0] = 0;
                                    if (Vars[0] > 1) Vars[0] = 1;
                                    if (Vars[1] < 0) Vars[1] = 0;
                                    if (Vars[1] > 1) Vars[1] = 1;
                                    if (Vars[2] < 0) Vars[2] = 0;
                                    if (Vars[2] > 1) Vars[2] = 1;
                                    if (Vars.Length > 3 && Vars[3] < 0) Vars[3] = 0;
                                    if (Vars.Length > 3 && Vars[3] > 1) Vars[3] = 1;
                                    if (v.FormatType == DataType.GL_BYTE || v.FormatType == DataType.GL_UNSIGNED_BYTE)
                                        if (Vars.Length > 3) p.Colors[i] = Color.FromArgb((int)(Vars[3] * 255), (int)(Vars[0] * 255), (int)(Vars[1] * 255), (int)(Vars[2] * 255));
                                        else p.Colors[i] = Color.FromArgb(255, (int)(Vars[0] * 255), (int)(Vars[1] * 255), (int)(Vars[2] * 255));
                                    else p.Colors[i] = Color.White;
                                    break;
                                case VertexAttributeUsage.TextureCoordinate0:
                                    p.TexCoords[i] = new Vector2(Vars[0], Vars[1]);
                                    break;
                                case VertexAttributeUsage.TextureCoordinate1:
                                    p.TexCoords2[i] = new Vector2(Vars[0], Vars[1]);
                                    break;
                                case VertexAttributeUsage.TextureCoordinate2:
                                    p.TexCoords3[i] = new Vector2(Vars[0], Vars[1]);
                                    break;
                                case VertexAttributeUsage.BoneIndex:
                                    {
                                        if (v.NrComponents == 1)
                                        {
                                            byte boneidx = VertexData[Offset + v.Offset];
                                            p.Vertex[i] = p.Vertex[i] * Model.Skeleton.GetMatrix((int)PrimitiveSet.RelatedBones[boneidx]); //SkeletonCtr.TransformByMtx(p.Vertex[i], Model.Skeleton.GetMatrix((int)PrimitiveSet.RelatedBones[boneidx]));//Vector3.Transform(p.Vertex[i], Model.Skeleton.GetMatrix((int)PrimitiveSets[0].RelatedBones[boneidx]));
                                        }
                                        else
                                        {
                                            bones = new byte[v.NrComponents];
                                            for (int q = 0; q < v.NrComponents; q++)
                                            {
                                                bones[q] = VertexData[Offset + v.Offset + q];
                                            }
                                        }
                                    }
                                    break;
                                case VertexAttributeUsage.BoneWeight:
                                    {
                                        if (bones.Length != 0)
                                        {
                                            //this doesn't work correct!
                                            //Vector3 dst = new Vector3(0, 0, 0);
                                            //for (int j = 0; j < v.NrComponents; j++)
                                            //{
                                            //	dst += p.Vertex[i] * Model.Skeleton.GetMatrix((int)PrimitiveSet.RelatedBones[bones[j]]) * Vars[j];// SkeletonCtr.TransformByMtx(p.Vertex[i], Model.Skeleton.GetMatrix((int)PrimitiveSet.RelatedBones[bones[j]])) * Vars[j];//Add4(dst, Mult4(Model.Skeleton.GetMatrix((int)PrimitiveSet.RelatedBones[bones[j]]), ((float)weights[j] * v.Scale)));
                                            //}
                                            //no transformations when no animation is used!
                                            //p.Vertex[i] = dst;
                                        }
                                        else
                                        {

                                        }
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        Offset += (int)VertexDataEntrySize;
                    }
                }
Example #22
0
 public virtual void GetVertexData(Polygon Destination, PrimitiveSet PrimitiveSet, CMDL Model)
 {
 }
Example #23
0
 public override void GetVertexData(Polygon Destination, PrimitiveSet PrimitiveSet, CMDL Model)
 {
     int count = Destination.Vertex.Length;
     switch (Usage)
     {
         //case VertexAttributeUsage.Position: Destination.Vertex = new Vector3[Vertices]; break;
         case VertexAttributeUsage.Tangent:
             break;
         case VertexAttributeUsage.Normal:
             Destination.Normals = new Vector3[count];
             for (int i = 0; i < count; i++)
             {
                 Destination.Normals[i] = new Vector3(Attributes[0], Attributes[1], Attributes[2]);
             }
             break;
         //case VertexAttributeUsage.Tangent: break;
         case VertexAttributeUsage.Color:
             Destination.Colors = new Color[count];
             for (int i = 0; i < count; i++)
             {
                 if (NrAttributes > 3) Destination.Colors[i] = Color.FromArgb((int)(Attributes[3] * 255), (int)(Attributes[0] * 255), (int)(Attributes[1] * 255), (int)(Attributes[2] * 255));
                 else Destination.Colors[i] = Color.FromArgb(255, (int)(Attributes[0] * 255), (int)(Attributes[1] * 255), (int)(Attributes[2] * 255));
             }
             break;
         case VertexAttributeUsage.TextureCoordinate0:
             Destination.TexCoords = new Vector2[count];
             for (int i = 0; i < count; i++)
             {
                 Destination.TexCoords[i] = new Vector2(Attributes[0], Attributes[1]);
             }
             break;
         case VertexAttributeUsage.TextureCoordinate1:
             Destination.TexCoords2 = new Vector2[count];
             for (int i = 0; i < count; i++)
             {
                 Destination.TexCoords2[i] = new Vector2(Attributes[0], Attributes[1]);
             }
             break;
         case VertexAttributeUsage.TextureCoordinate2:
             Destination.TexCoords3 = new Vector2[count];
             for (int i = 0; i < count; i++)
             {
                 Destination.TexCoords3[i] = new Vector2(Attributes[0], Attributes[1]);
             }
             break;
         case VertexAttributeUsage.BoneIndex:
             Matrix34 mtx = Model.Skeleton.GetMatrix((int)Attributes[0]);
             for (int i = 0; i < count; i++)
             {
                 Destination.Vertex[i] *= mtx;
             }
             break;
         case VertexAttributeUsage.BoneWeight: break;//tmp
         default:
             break;
     }
 }