Пример #1
0
        public static LightList <int> Tessellate(LightList <float> data, LightList <int> holeIndices, LightList <int> output = null)
        {
            bool hasHoles  = holeIndices != null && holeIndices.Count > 0;
            int  outerLen  = hasHoles ? holeIndices[0] * 2 : data.Count;
            Node outerNode = LinkedList(data, 0, outerLen, true);

            output = output ?? new LightList <int>(data.Count / 2);

            if (outerNode == null)
            {
                return(output);
            }

            var minX    = float.PositiveInfinity;
            var minY    = float.PositiveInfinity;
            var maxX    = float.NegativeInfinity;
            var maxY    = float.NegativeInfinity;
            var invSize = default(float);

            if (hasHoles)
            {
                outerNode = EliminateHoles(data, holeIndices, outerNode);
            }

            // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
            if (data.Count > 80 * 2)
            {
                for (int i = 0; i < outerLen; i += 2)
                {
                    float x = data[i];
                    float y = data[i + 1];

                    if (x < minX)
                    {
                        minX = x;
                    }

                    if (y < minY)
                    {
                        minY = y;
                    }

                    if (x > maxX)
                    {
                        maxX = x;
                    }

                    if (y > maxY)
                    {
                        maxY = y;
                    }
                }

                // minX, minY and invSize are later used to transform coords into integers for z-order calculation
                invSize = Math.Max(maxX - minX, maxY - minY);
                invSize = invSize != 0 ? 1 / invSize : 0;
            }

            EarcutLinked(outerNode, output, minX, minY, invSize, 0);

            return(output);
        }
Пример #2
0
        private bool ParseDeclaration(ref ASTNode node)
        {
            AttributeNode             attrNode   = null;
            LightList <AttributeNode> attributes = LightList <AttributeNode> .Get();

            while (ParseAttribute(ref attrNode))
            {
                attributes.Add(attrNode);
                if (tokenStream.Current != ExpressionTokenType.ArrayAccessOpen)
                {
                    break;
                }
            }

            if (attributes.size == 0)
            {
                LightList <AttributeNode> .Release(ref attributes);
            }

            if (tokenStream.Current != ExpressionTokenType.Identifier)
            {
                return(false);
            }

            // modifiers? -> returnType -> name -> signature -> openBrace * closeBrace

            tokenStream.Save();

            bool isStatic = false;

            if (tokenStream.Current == "static")
            {
                isStatic = true;
                tokenStream.Advance();
            }

            ExpressionParser            parser    = new ExpressionParser(tokenStream);
            StructList <LambdaArgument> signature = null;
            TypeLookup typeLookup = default;

            if (!parser.ParseTypePath(ref typeLookup))
            {
                goto fail;
            }

            tokenStream.Set(parser.GetTokenPosition());
            parser.Release(false);

            if (tokenStream.Current != ExpressionTokenType.Identifier)
            {
                goto fail;
            }

            string name = tokenStream.Current.value;

            tokenStream.Advance();

            // if semi colon then we have a field!
            if (tokenStream.Current == ExpressionTokenType.SemiColon)
            {
                tokenStream.Advance();
                node = new FieldNode()
                {
                    name       = name,
                    isStatic   = isStatic,
                    attributes = attributes,
                    typeLookup = typeLookup
                };
                return(true);
            }

            if (tokenStream.Current != ExpressionTokenType.ParenOpen)
            {
                goto fail;
            }

            signature = StructList <LambdaArgument> .Get();

            if (tokenStream.NextTokenIs(ExpressionTokenType.ParenClose))
            {
                tokenStream.Advance(2);
            }
            else
            {
                int matchingIndex = tokenStream.FindMatchingIndex(ExpressionTokenType.ParenOpen, ExpressionTokenType.ParenClose);

                if (matchingIndex == -1)
                {
                    goto fail;
                }

                TokenStream subStream = tokenStream.AdvanceAndReturnSubStream(matchingIndex);
                subStream.Advance();
                tokenStream.Advance();
                if (!ExpressionParser.ParseSignature(subStream, signature))
                {
                    goto fail;
                }

                for (int i = 0; i < signature.size; i++)
                {
                    if (signature.array[i].type == null)
                    {
                        throw new ParseException($"When defining a method you must specify a type for all arguments. Found identifier {signature.array[i].identifier} but no type was given.");
                    }
                }
            }

            if (tokenStream.Current != ExpressionTokenType.ExpressionOpen)
            {
                goto fail;
            }

            BlockNode block = ParseBlock();

            node = new MethodNode()
            {
                body             = block,
                returnTypeLookup = typeLookup,
                attributes       = attributes,
                name             = name,
                isStatic         = isStatic,
                signatureList    = signature != null?signature.ToArray() : s_EmptySignature
            };

            StructList <LambdaArgument> .Release(ref signature);

            parser.Release(false);

            return(true);

fail:
            {
                tokenStream.Restore();
                parser.Release(false);
                typeLookup.Release();
                signature?.Release();
                return(false);
            }
        }
Пример #3
0
		/// <summary>
		///		Render those objects in the transparent pass list which have shadow casting forced on
		/// </summary>
		/// <remarks>
		///		This function is intended to be used to render the shadows of transparent objects which have
		///		transparency_casts_shadows set to 'on' in their material
		/// </remarks>
		/// <param name="list"></param>
		/// <param name="doLightIteration"></param>
		/// <param name="manualLightList"></param>
		protected virtual void RenderTransparentShadowCasterObjects( List<RenderablePass> list,
																	 bool doLightIteration,
																	 LightList manualLightList )
		{
			// ----- TRANSPARENT LOOP as in RenderTransparentObjects, but changed a bit -----
			for ( int i = 0; i < list.Count; i++ )
			{
				RenderablePass rp = list[ i ];

				// only render this pass if it's being forced to cast shadows
				if ( rp.pass.Parent.Parent.TransparencyCastsShadows )
				{
					this.SetPass( rp.pass );
					this.RenderSingleObject( rp.renderable, rp.pass, doLightIteration, manualLightList );
				}
			}
		}
Пример #4
0
 public void AddKeyFrameNode(KeyFrameNode keyFrameNode)
 {
     keyframeNodes = keyframeNodes ?? new LightList <KeyFrameNode>(4);
     keyframeNodes.Add(keyFrameNode);
 }
Пример #5
0
		/// <summary>
		///		Overriden from SceneManager.
		/// </summary>
		protected override void RenderSingleObject( IRenderable renderable, Pass pass, bool doLightIteration,
		                                            LightList manualLightList )
		{
			if ( renderable is BspGeometry )
			{
				// Render static level geometry
				if ( doLightIteration )
				{
					// render all geometry without lights first
					RenderStaticGeometry();

					// render geometry affected by each visible light
					foreach ( Light l in lightsAffectingFrustum )
					{
						RenderTextureLighting( l );
					}
				}
				else
				{
					if ( manualLightList.Count == 0 )
					{
						if ( illuminationStage == IlluminationRenderStage.RenderReceiverPass )
						{
							// texture shadows
							RenderTextureShadowOnGeometry();
						}
						else
						{
							// ambient stencil pass, render geometry without lights
							RenderStaticGeometry();
						}
					}
					else
					{
						// render only geometry affected by the provided light
						foreach ( Light l in manualLightList )
						{
							RenderTextureLighting( l );
						}
					}
				}
			}
			else
			{
				base.RenderSingleObject( renderable, pass, doLightIteration, manualLightList );
			}
		}
Пример #6
0
		/// <summary>
		///		Renders a set of solid objects.
		/// </summary>
		protected virtual void RenderSolidObjects( System.Collections.SortedList list,
												   bool doLightIteration,
												   LightList manualLightList )
		{
			// ----- SOLIDS LOOP -----
			for ( int i = 0; i < list.Count; i++ )
			{
				RenderableList renderables = (RenderableList)list.GetByIndex( i );

				// bypass if this group is empty
				if ( renderables.Count == 0 )
				{
					continue;
				}

				Pass pass = (Pass)list.GetKey( i );

				// Give SM a chance to eliminate this pass
				if ( !this.ValidatePassForRendering( pass ) )
				{
					continue;
				}

				// For solids, we try to do each pass in turn
				Pass usedPass = this.SetPass( pass );

				// render each object associated with this rendering pass
				for ( int r = 0; r < renderables.Count; r++ )
				{
					IRenderable renderable = (IRenderable)renderables[ r ];

					// Give SM a chance to eliminate
					if ( !this.ValidateRenderableForRendering( usedPass, renderable ) )
					{
						continue;
					}

					// Render a single object, this will set up auto params if required
					this.RenderSingleObject( renderable, usedPass, doLightIteration, manualLightList );
				}
			}
		}
Пример #7
0
 public abstract void OnChildrenChanged(LightList <AwesomeLayoutBox> childList);
Пример #8
0
		/// <summary>
		///    
		/// </summary>
		public void SetCurrentLightList( LightList lightList )
		{
			currentLightList = lightList;
		}
Пример #9
0
        public static CompiledTemplateData LoadRuntimeTemplates(Type type, TemplateSettings templateSettings)
        {
            CompiledTemplateData compiledTemplateData = TemplateCompiler.CompileTemplates(type, templateSettings);

            // Stopwatch stopwatch = Stopwatch.StartNew();

            Func <UIElement, TemplateScope, UIElement>[] templates = new Func <UIElement, TemplateScope, UIElement> [compiledTemplateData.compiledTemplates.size];
            Action <UIElement, UIElement>[] bindings = new Action <UIElement, UIElement> [compiledTemplateData.compiledBindings.size];
            Func <UIElement, UIElement, TemplateScope, UIElement>[] slots = new Func <UIElement, UIElement, TemplateScope, UIElement> [compiledTemplateData.compiledSlots.size];
            TemplateMetaData[] templateMetaData = new TemplateMetaData[compiledTemplateData.compiledTemplates.size];
            OrderablePartitioner <Tuple <int, int> > partition;

            if (templateMetaData.Length < 10)
            {
                for (int i = 0; i < templateMetaData.Length; i++)
                {
                    templates[i] = (Func <UIElement, TemplateScope, UIElement>)compiledTemplateData.compiledTemplates[i].templateFn.Compile();
                }
            }
            else
            {
                partition = Partitioner.Create(0, templateMetaData.Length);

                Parallel.ForEach(partition, (range, loopState) => {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        templates[i] = (Func <UIElement, TemplateScope, UIElement>)compiledTemplateData.compiledTemplates[i].templateFn.Compile();
                    }
                });
            }

            if (compiledTemplateData.compiledSlots.size < 10)
            {
                for (int i = 0; i < compiledTemplateData.compiledSlots.size; i++)
                {
                    slots[i] = (Func <UIElement, UIElement, TemplateScope, UIElement>)compiledTemplateData.compiledSlots[i].templateFn.Compile();
                }
            }
            else
            {
                partition = Partitioner.Create(0, compiledTemplateData.compiledSlots.size);
                Parallel.ForEach(partition, (range, loopState) => {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        slots[i] = (Func <UIElement, UIElement, TemplateScope, UIElement>)compiledTemplateData.compiledSlots[i].templateFn.Compile();
                    }
                });
            }

            if (bindings.Length < 10)
            {
                for (int i = 0; i < bindings.Length; i++)
                {
                    try {
                        bindings[i] = (Action <UIElement, UIElement>)compiledTemplateData.compiledBindings[i].bindingFn.Compile();
                    }
                    catch (Exception e) {
                        Debug.Log("binding " + compiledTemplateData.compiledBindings[i].bindingFn.ToCSharpCode());
                        Debug.Log(e);
                    }
                }
            }
            else
            {
                partition = Partitioner.Create(0, bindings.Length);
                Parallel.ForEach(partition, (range, loopState) => {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        try {
                            bindings[i] = (Action <UIElement, UIElement>)compiledTemplateData.compiledBindings[i].bindingFn.Compile();
                        }
                        catch (Exception e) {
                            Debug.Log("binding " + compiledTemplateData.compiledBindings[i].bindingFn.ToCSharpCode());
                            Debug.Log(e);
                        }
                    }
                });
            }

            LightList <UIStyleGroupContainer> styleList = new LightList <UIStyleGroupContainer>(128);

            StyleSheet[] sheets = compiledTemplateData.styleImporter.GetImportedStyleSheets();

            for (int i = 0; i < sheets.Length; i++)
            {
                StyleSheet sheet = sheets[i];
                styleList.EnsureAdditionalCapacity(sheet.styleGroupContainers.Length);
                for (int j = 0; j < sheet.styleGroupContainers.Length; j++)
                {
                    styleList.array[styleList.size++] = sheet.styleGroupContainers[j];
                }
            }

            for (int i = 0; i < templateMetaData.Length; i++)
            {
                templateMetaData[i]          = compiledTemplateData.compiledTemplates[i].templateMetaData;
                templateMetaData[i].styleMap = styleList.array;
                templateMetaData[i].BuildSearchMap();
            }

            Dictionary <int, Func <ConstructedElement> > constructorFnMap = new Dictionary <int, Func <ConstructedElement> >(37);

            ConstructorInfo constructedTypeCtor = typeof(ConstructedElement).GetConstructor(new Type[] { typeof(int), typeof(UIElement) });

            System.Diagnostics.Debug.Assert(constructedTypeCtor != null, nameof(constructedTypeCtor) + " != null");

            compiledTemplateData.bindings         = bindings;
            compiledTemplateData.slots            = slots;
            compiledTemplateData.templates        = templates;
            compiledTemplateData.templateMetaData = templateMetaData;
            compiledTemplateData.constructorFnMap = constructorFnMap;
            compiledTemplateData.constructElement = (typeId) => compiledTemplateData.constructorFnMap[typeId].Invoke();

            // stopwatch.Stop();
            // Debug.Log("Loaded UIForia templates in " + stopwatch.Elapsed.TotalSeconds.ToString("F2") + " seconds");

            return(compiledTemplateData);
        }
Пример #10
0
 public LinqBindingSystem()
 {
     this.rootNodes = new LightList <UIElement>();
 }
Пример #11
0
 public AnimationSystem()
 {
     thisFrame = new LightList <AnimationTask>();
     nextFrame = new LightList <AnimationTask>();
 }
Пример #12
0
        public static MemberAccessExpressionNode MemberAccessExpressionNode(string identifier, LightList <ASTNode> parts)
        {
            MemberAccessExpressionNode accessExpressionNode = s_MemberAccessExpressionPool.Get();

            accessExpressionNode.identifier = identifier;
            accessExpressionNode.parts      = parts;
            return(accessExpressionNode);
        }
Пример #13
0
 public ListRecordStore()
 {
     store = new LightList <T>(16);
 }
Пример #14
0
 public UITaskGroup()
 {
     this.taskStatusPairs = new LightList <TaskStatusPair>(4);
 }
Пример #15
0
 public override void OnChildrenChanged(LightList <AwesomeLayoutBox> childList)
 {
     this.childList = this.childList ?? new LightList <AwesomeLayoutBox>(childList.size);
     this.childList.AddRange(childList);
 }
Пример #16
0
		public virtual void SetCurrentLightList( LightList lightList )
		{
			this.currentLightList = lightList;
			for ( int i = 0; i < lightList.Count && i < Config.MaxSimultaneousLights; ++i )
			{
				this.spotlightViewProjMatrixDirty[ i ] = true;
				this.spotlightWorldViewProjMatrixDirty[ i ] = true;
			}
		}
Пример #17
0
 public StyleNodeContainer()
 {
     this.children = new LightList <StyleASTNode>(2);
 }
Пример #18
0
        public override void UseLights( LightList lightList, int limit )
        {
            var activeDevice = ActiveD3D9Device;
            var i = 0;

            // Axiom specific: [indexer] wont create an entry in the map
            if (!_currentLights.ContainsKey(activeDevice))
                _currentLights.Add(activeDevice, 0);

            for ( ; i < limit && i < lightList.Count; i++ )
            {
                SetD3D9Light( i, lightList[ i ] );
            }

            for (; i < _currentLights[activeDevice]; i++)
            {
                SetD3D9Light( i, null );
            }

            _currentLights[activeDevice] = Utility.Min(limit, lightList.Count);
        }
Пример #19
0
 public StyleSheetCompiler(StyleSheetImporter styleSheetImporter, ResourceManager resourceManager)
 {
     this.styleSheetImporter = styleSheetImporter;
     this.resourceManager    = resourceManager;
     this.scratchGroupList   = new LightList <UIStyleGroup>(32);
 }
Пример #20
0
		/// <summary>
		///		Render a single shadow volume to the stencil buffer.
		/// </summary>
		protected void RenderSingleShadowVolumeToStencil( ShadowRenderable sr,
														  bool zfail,
														  bool stencil2sided,
														  LightList manualLightList,
														  bool isSecondPass )
		{
			// Render a shadow volume here
			//  - if we have 2-sided stencil, one render with no culling
			//  - otherwise, 2 renders, one with each culling method and invert the ops
			if ( !isSecondPass )
			{
				this.SetShadowVolumeStencilState( false, zfail, stencil2sided );
				this.RenderSingleObject( sr, this.shadowStencilPass, false, manualLightList );
			}

			if ( !stencil2sided && isSecondPass )
			{
				// Second pass
				this.SetShadowVolumeStencilState( true, zfail, false );
				this.RenderSingleObject( sr, this.shadowStencilPass, false );
			}

			// Do we need to render a debug shadow marker?
			if ( this.showDebugShadows && ( isSecondPass || stencil2sided ) )
			{
				// reset stencil & colour ops
				this.targetRenderSystem.SetStencilBufferParams();
				this.SetPass( this.shadowDebugPass );
				this.RenderSingleObject( sr, this.shadowDebugPass, false, manualLightList );
				this.targetRenderSystem.SetColorBufferWriteEnabled( false, false, false, false );
			}
		}
Пример #21
0
        private AnimationOptions CompileAnimationOptions(AnimationRootNode animNode)
        {
            AnimationOptions options = new AnimationOptions();

            if (animNode.optionNodes == null)
            {
                return(options);
            }

            LightList <AnimationOptionNode> optionNodes = animNode.optionNodes;

            if (optionNodes == null)
            {
                return(options);
            }

            for (int i = 0; i < optionNodes.Count; i++)
            {
                string       optionName = optionNodes[i].optionName.ToLower();
                StyleASTNode value      = optionNodes[i].value;

                switch (optionName)
                {
                case "duration":
                    options.duration = StylePropertyMappers.MapUITimeMeasurement(value, context);
                    break;

                case "iterations":
                    options.iterations = (int)StylePropertyMappers.MapNumberOrInfinite(value, context);
                    break;

                case "looptime":
                    options.loopTime = StylePropertyMappers.MapNumber(value, context);
                    break;

                case "delay":
                    options.delay = StylePropertyMappers.MapUITimeMeasurement(value, context);
                    break;

                case "direction":
                    options.direction = StylePropertyMappers.MapEnum <AnimationDirection>(value, context);
                    break;

                case "looptype":
                    options.loopType = StylePropertyMappers.MapEnum <AnimationLoopType>(value, context);
                    break;

                case "forwardstartdelay":
                    options.forwardStartDelay = (int)StylePropertyMappers.MapNumber(value, context);
                    break;

                case "reversestartdelay":
                    options.reverseStartDelay = (int)StylePropertyMappers.MapNumber(value, context);
                    break;

                case "timingfunction":
                    options.timingFunction = StylePropertyMappers.MapEnum <EasingFunction>(value, context);
                    break;

                default:
                    throw new CompileException(optionNodes[i], "Invalid option argument for animation");
                }
            }

            return(options);
        }
Пример #22
0
		/// <summary>
		///		Render a group with the added complexity of additive stencil shadows.
		/// </summary>
		/// <param name="group">Render queue group.</param>
		protected virtual void RenderAdditiveStencilShadowedQueueGroupObjects( RenderQueueGroup group )
		{
			LightList tempLightList = new LightList();

			foreach ( RenderPriorityGroup priorityGroup in group.PriorityGroups.Values )
			{
				// sort the group first
				priorityGroup.Sort( this.cameraInProgress );

				// Clear light list
				tempLightList.Clear();

				// Render all the ambient passes first, no light iteration, no lights
				this.illuminationStage = IlluminationRenderStage.Ambient;
				this.RenderSolidObjects( priorityGroup.solidPasses, false, tempLightList );
				// Also render any objects which have receive shadows disabled
				this.renderingNoShadowQueue = true;
				this.RenderSolidObjects( priorityGroup.solidPassesNoShadow, true );
				this.renderingNoShadowQueue = false;

				// Now iterate per light
				this.illuminationStage = IlluminationRenderStage.PerLight;

				foreach ( Light light in lightsAffectingFrustum )
				{
					// Set light state

					if ( light.CastShadows )
					{
						// Clear stencil
						this.targetRenderSystem.ClearFrameBuffer( FrameBufferType.Stencil );
						this.RenderShadowVolumesToStencil( light, this.cameraInProgress );
						// turn stencil check on
						this.targetRenderSystem.StencilCheckEnabled = true;
						// NB we render where the stencil is equal to zero to render lit areas
						this.targetRenderSystem.SetStencilBufferParams( CompareFunction.Equal, 0 );
					}

					// render lighting passes for this light
					tempLightList.Clear();
					tempLightList.Add( light );

					this.RenderSolidObjects( priorityGroup.solidPassesDiffuseSpecular, false, tempLightList );

					// Reset stencil params
					this.targetRenderSystem.SetStencilBufferParams();
					this.targetRenderSystem.StencilCheckEnabled = false;
					this.targetRenderSystem.SetDepthBufferParams();
				} // for each light

				// Now render decal passes, no need to set lights as lighting will be disabled
				this.illuminationStage = IlluminationRenderStage.Decal;
				this.RenderSolidObjects( priorityGroup.solidPassesDecal, false );
			} // for each priority

			// reset lighting stage
			this.illuminationStage = IlluminationRenderStage.None;

			// Iterate again
			foreach ( RenderPriorityGroup priorityGroup in group.PriorityGroups.Values )
			{
				// Do transparents
				this.RenderTransparentObjects( priorityGroup.transparentPasses, true );
			} // for each priority
		}
Пример #23
0
        // public StyleSheet Compile(string filePath, string contents) {
        //     return Compile(filePath, StyleParser.Parse(contents));
        // }

        // todo -- deprecate, use other method
        public StyleSheet Compile(string filePath, LightList <StyleASTNode> rootNodes, MaterialDatabase materialDatabase = default)
        {
            try {
                context = new StyleSheetConstantImporter(styleSheetImporter).CreateContext(rootNodes, materialDatabase);
                context.resourceManager = resourceManager;

                //       context = new StyleCompileContext(); // todo resolve constants. should be done a per file level, should store all used constants without needing to later reference other files
                // StyleCompileContext.Create(styleSheetImporter) //new StyleSheetConstantImporter(styleSheetImporter).CreateContext(rootNodes);
            }
            catch (CompileException e) {
                e.SetFileName(filePath);
                throw;
            }

            context.fileName = filePath;

            // todo add imported style groups

            rootNodes.Sort((node1, node2) => {
                int left  = (int)node1.type;
                int right = (int)node2.type;
                return(left - right);
            });

            int containerCount = 0;
            int animationCount = 0;
            int soundCount     = 0;

            for (int index = 0; index < rootNodes.Count; index++)
            {
                switch (rootNodes[index])
                {
                case StyleRootNode _:
                    containerCount++;
                    break;

                case AnimationRootNode _:
                case SpriteSheetNode _:
                    animationCount++;
                    break;

                case SoundRootNode _:
                    soundCount++;
                    break;
                }
            }

            StyleSheet styleSheet = new StyleSheet(
                styleSheetImporter.ImportedStyleSheetCount,
                context.constants?.ToArray(),
                containerCount > 0
                    ? new UIStyleGroupContainer[containerCount]
                    : ArrayPool <UIStyleGroupContainer> .Empty,
                animationCount > 0
                    ? new AnimationData[animationCount]
                    : ArrayPool <AnimationData> .Empty,
                soundCount > 0
                    ? new UISoundData[soundCount]
                    : ArrayPool <UISoundData> .Empty
                );

            int containerIndex = 0;
            int animationIndex = 0;
            int soundIndex     = 0;

            for (int index = 0; index < rootNodes.Count; index++)
            {
                switch (rootNodes[index])
                {
                // we sorted the root nodes so all animations run first
                case SpriteSheetNode spriteSheetNode:
                    styleSheet.animations[animationIndex] = CompileSpriteSheetAnimation(spriteSheetNode, styleSheet.animations, styleSheet.sounds);
                    animationIndex++;
                    break;

                case AnimationRootNode animNode:
                    styleSheet.animations[animationIndex] = CompileAnimation(animNode, styleSheet.animations, styleSheet.sounds);
                    animationIndex++;
                    break;

                case SoundRootNode soundRootNode:
                    styleSheet.sounds[soundIndex] = CompileSound(soundRootNode);
                    soundIndex++;
                    break;

                case StyleRootNode styleRoot:
                    styleSheet.styleGroupContainers[containerIndex]            = CompileStyleGroup(styleRoot, styleSheet.animations, styleSheet.sounds);
                    styleSheet.styleGroupContainers[containerIndex].styleSheet = styleSheet;
                    containerIndex++;
                    break;
                }
            }

            context.Release();
            return(styleSheet);
        }
        /// <summary>
        ///		Overriden from SceneManager.
        /// </summary>
        /// <param name="position">The position at which to evaluate the list of lights</param>
        /// <param name="radius">The bounding radius to test</param>
        /// <param name="destList">List to be populated with ordered set of lights; will be cleared by this method before population.</param>
        protected override void PopulateLightList(Vector3 position, float radius, LightList destList)
        {
            BspNode positionNode = level.FindLeaf(position);
            BspNode[] lightNodes = new BspNode[lightList.Count];

            for (int i = 0; i < lightList.Count; i++)
            {
                Light light = lightList[i];
                lightNodes[i] = (BspNode) level.objectToNodeMap.FindFirst(light);
            }

            // Trawl of the lights that are visible from position, then sort
            destList.Clear();
            float squaredRadius = radius * radius;

            // loop through the scene lights an add ones in range and visible from positionNode
            for(int i = 0; i < lightList.Count; i++)
            {
                TextureLight light = (TextureLight) lightList[i];

                if(light.IsVisible && level.IsLeafVisible(positionNode, lightNodes[i]))
                {
                    if(light.Type == LightType.Directional)
                    {
                        // no distance
                        light.TempSquaredDist = 0.0f;
                        destList.Add(light);
                    }
                    else
                    {
                        light.TempSquaredDist = (light.DerivedPosition - position).LengthSquared;
                        light.TempSquaredDist -= squaredRadius;
                        // only add in-range lights
                        float range = light.AttenuationRange;
                        if(light.TempSquaredDist <= (range * range))
                        {
                            destList.Add(light);
                        }
                    }
                } // if
            } // for

            // Sort Destination light list.
            // TODO: Not needed yet since the current LightList is a sorted list under the hood already
            //destList.Sort();
        }
Пример #25
0
        private AnimationOptions CompileSpriteSheetOptions(SpriteSheetNode node)
        {
            AnimationOptions options = new AnimationOptions();

            LightList <StyleASTNode> spriteSheetProperties = node.children;

            if (spriteSheetProperties == null)
            {
                return(options);
            }

            for (int i = 0; i < spriteSheetProperties.Count; i++)
            {
                if (spriteSheetProperties[i] is PropertyNode property)
                {
                    string       optionName = property.identifier.ToLower();
                    StyleASTNode value      = property.children[0];

                    switch (optionName)
                    {
                    case "iterations":
                        options.iterations = (int)StylePropertyMappers.MapNumberOrInfinite(value, context);
                        break;

                    case "delay":
                        options.delay = StylePropertyMappers.MapUITimeMeasurement(value, context);
                        break;

                    case "duration":
                        options.duration = StylePropertyMappers.MapUITimeMeasurement(value, context);
                        break;

                    case "looptype":
                        options.loopType = StylePropertyMappers.MapEnum <AnimationLoopType>(value, context);
                        break;

                    case "direction":
                        options.direction = StylePropertyMappers.MapEnum <AnimationDirection>(value, context);
                        break;

                    case "forwardstartdelay":
                        options.forwardStartDelay = (int)StylePropertyMappers.MapNumber(value, context);
                        break;

                    case "reversestartdelay":
                        options.reverseStartDelay = (int)StylePropertyMappers.MapNumber(value, context);
                        break;

                    case "fps":
                        options.fps = (int)StylePropertyMappers.MapNumber(value, context);
                        break;

                    case "startframe":
                        options.startFrame = (int)StylePropertyMappers.MapNumber(value, context);
                        break;

                    case "endframe":
                        options.endFrame = (int)StylePropertyMappers.MapNumber(value, context);
                        break;

                    case "pathprefix":
                        options.pathPrefix = StylePropertyMappers.MapString(value, context);
                        break;

                    default:
                        throw new CompileException(property, "Invalid option argument for animation");
                    }
                }
                else
                {
                    throw new CompileException(spriteSheetProperties[i], "Invalid option argument for animation");
                }
            }

            return(options);
        }
Пример #26
0
 public abstract void Filter(UIElement origin, int templateId, LightList <UIElement> resultSet);
Пример #27
0
        private void CompileStyleGroups(StyleNodeContainer root, StyleType styleType, LightList <UIStyleGroup> groups, UIStyleGroup targetGroup, AnimationData[] styleSheetAnimations, UISoundData[] uiSoundData)
        {
            for (int index = 0; index < root.children.Count; index++)
            {
                StyleASTNode node = root.children[index];
                switch (node)
                {
                case SelectNode selectNode:
                    break;

                case PropertyNode propertyNode:
                    // add to normal ui style set
                    StylePropertyMappers.MapProperty(targetGroup.normal.style, propertyNode, context);
                    break;

                case AttributeNodeContainer attribute:
                    if (root is AttributeNodeContainer)
                    {
                        throw new CompileException(attribute, "You cannot nest attribute group definitions.");
                    }

                    UIStyleGroup attributeGroup = new UIStyleGroup();
                    attributeGroup.normal    = UIStyleRunCommand.CreateInstance();
                    attributeGroup.name      = root.identifier;
                    attributeGroup.rule      = MapAttributeContainerToRule(attribute);
                    attributeGroup.styleType = styleType;
                    groups.Add(attributeGroup);
                    CompileStyleGroups(attribute, styleType, groups, attributeGroup, styleSheetAnimations, uiSoundData);

                    break;

                case RunNode runNode:
                    UIStyleRunCommand cmd = new UIStyleRunCommand()
                    {
                        style       = targetGroup.normal.style,
                        runCommands = targetGroup.normal.runCommands ?? new LightList <IRunCommand>(4)
                    };

                    if (runNode.command is AnimationCommandNode animationCommandNode)
                    {
                        MapAnimationCommand(styleSheetAnimations, cmd, animationCommandNode);
                    }
                    else if (runNode.command is SoundCommandNode soundCommandNode)
                    {
                        MapSoundCommand(uiSoundData, cmd, soundCommandNode);
                    }

                    targetGroup.normal = cmd;
                    break;

                case StyleStateContainer styleContainer:
                    if (styleContainer.identifier == "hover")
                    {
                        UIStyleRunCommand uiStyleRunCommand = targetGroup.hover;
                        uiStyleRunCommand.style = uiStyleRunCommand.style ?? new UIStyle();
                        MapProperties(styleSheetAnimations, uiSoundData, ref uiStyleRunCommand, styleContainer.children);
                        targetGroup.hover = uiStyleRunCommand;
                    }
                    else if (styleContainer.identifier == "focus")
                    {
                        UIStyleRunCommand uiStyleRunCommand = targetGroup.focused;
                        uiStyleRunCommand.style = uiStyleRunCommand.style ?? new UIStyle();
                        MapProperties(styleSheetAnimations, uiSoundData, ref uiStyleRunCommand, styleContainer.children);
                        targetGroup.focused = uiStyleRunCommand;
                    }
                    else if (styleContainer.identifier == "active")
                    {
                        UIStyleRunCommand uiStyleRunCommand = targetGroup.active;
                        uiStyleRunCommand.style = uiStyleRunCommand.style ?? new UIStyle();
                        MapProperties(styleSheetAnimations, uiSoundData, ref uiStyleRunCommand, styleContainer.children);
                        targetGroup.active = uiStyleRunCommand;
                    }
                    else
                    {
                        throw new CompileException(styleContainer, $"Unknown style state '{styleContainer.identifier}'. Please use [hover], [focus] or [active] instead.");
                    }

                    break;

                default:
                    throw new CompileException(node, $"You cannot have a {node} at this level.");
                }
            }
        }
Пример #28
0
        private bool ParseIfStatement(ref ASTNode node)
        {
            if (tokenStream.Current != ExpressionTokenType.If)
            {
                return(false);
            }

            LightList <ElseIfNode> statements = LightList <ElseIfNode> .Get();

            tokenStream.Advance();

            ASTNode condition = null;

            if (!ParseParenExpression(ref condition))
            {
                throw new ParseException("Expected a condition statement wrapped in parentheses but failed.");
            }

            BlockNode thenBlock = ParseBlock();

            if (thenBlock == null)
            {
                throw new ParseException("Expected a block statement following an if statement but failed to parse the block");
            }

            if (tokenStream.Current != ExpressionTokenType.ElseIf && tokenStream.Current != ExpressionTokenType.Else)
            {
                node = new IfStatementNode()
                {
                    // elseIfStatements = statements.ToArray(),
                    condition = condition,
                    thenBlock = thenBlock
                };
                return(true);
            }

            while (tokenStream.Current == ExpressionTokenType.ElseIf)
            {
                tokenStream.Advance();

                ASTNode elseIfCondition = null;

                if (!ParseParenExpression(ref elseIfCondition))
                {
                    throw new ParseException("Expected a condition statement wrapped in parentheses but failed.");
                }

                BlockNode block = ParseBlock();

                if (block == null)
                {
                    throw new ParseException("Expected a block statement following an if statement but failed to parse the block");
                }

                statements.Add(new ElseIfNode()
                {
                    condition = elseIfCondition,
                    thenBlock = block
                });
            }

            BlockNode elseBlock = null;

            if (tokenStream.Current == ExpressionTokenType.Else)
            {
                tokenStream.Advance();
                elseBlock = ParseBlock();

                if (elseBlock == null)
                {
                    throw new ParseException("Expected a block statement following an else statement but failed to parse the block");
                }
            }

            node = new IfStatementNode()
            {
                condition        = condition,
                thenBlock        = thenBlock,
                elseIfStatements = statements.size == 0 ? null : statements.ToArray(),
                elseBlock        = elseBlock
            };

            statements.Release();

            return(true);
        }
Пример #29
0
 public RoutingSystem()
 {
     this.m_Routers = new LightList <Router>();
 }
Пример #30
0
 internal Enumerator(LightList <T> list)
 {
     this.list    = list;
     this.index   = 0;
     this.current = default(T);
 }
Пример #31
0
 public void PushBlock()
 {
     statementStacks.Push(LightList <Expression> .Get());
 }
Пример #32
0
        private static Type ResolveBaseTypePath(TypeLookup typeLookup, IReadOnlyList <string> namespaces)
        {
            Type retn = ResolveSimpleType(typeLookup.typeName);

            if (retn != null)
            {
                return(retn);
            }

            string baseTypeName = "." + typeLookup.GetBaseTypeName(); // save some string concat

            if (!string.IsNullOrEmpty(typeLookup.namespaceName))
            {
                LightList <Assembly> assemblies = s_NamespaceMap.GetOrDefault(typeLookup.namespaceName);

                if (assemblies == null)
                {
                    throw new TypeResolutionException($"No loaded assemblies found for namespace {typeLookup.namespaceName}");
                }

                string typename = typeLookup.namespaceName + baseTypeName;

                for (int a = 0; a < assemblies.Count; a++)
                {
                    retn = assemblies[a].GetType(typename);
                    if (retn != null)
                    {
                        return(retn);
                    }
                }

                LightList <Assembly> lastDitchAssemblies = s_NamespaceMap.GetOrDefault("null");
                if (lastDitchAssemblies != null)
                {
                    typename = typeLookup.typeName;
                    for (int a = 0; a < lastDitchAssemblies.Count; a++)
                    {
                        retn = lastDitchAssemblies[a].GetType(typename);
                        if (retn != null)
                        {
                            return(retn);
                        }
                    }
                }
            }
            else
            {
                if (namespaces != null)
                {
                    for (int i = 0; i < namespaces.Count; i++)
                    {
                        LightList <Assembly> assemblies = s_NamespaceMap.GetOrDefault(namespaces[i]);
                        if (assemblies == null)
                        {
                            continue;
                        }

                        string typename = namespaces[i] + baseTypeName;
                        for (int a = 0; a < assemblies.Count; a++)
                        {
                            retn = assemblies[a].GetType(typename);
                            if (retn != null)
                            {
                                return(retn);
                            }
                        }
                    }
                }

                LightList <Assembly> lastDitchAssemblies = s_NamespaceMap.GetOrDefault("null");
                if (lastDitchAssemblies != null)
                {
                    string typename = typeLookup.typeName;
                    for (int a = 0; a < lastDitchAssemblies.Count; a++)
                    {
                        retn = lastDitchAssemblies[a].GetType(typename);
                        if (retn != null)
                        {
                            return(retn);
                        }
                    }
                }
            }

            if (namespaces != null && namespaces.Count > 0 && namespaces[0] != string.Empty)
            {
                string checkedNamespaces = string.Join(",", namespaces.ToArray());
                throw new TypeResolutionException($"Unable to resolve type {typeLookup}. Looked in namespaces: {checkedNamespaces}");
            }
            else
            {
                throw new TypeResolutionException($"Unable to resolve type {typeLookup}.");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="lightList"></param>
        /// <param name="limit"></param>
        public override void UseLights(LightList lightList, int limit)
        {
            // save previous modelview matrix
            Gl.glMatrixMode(Gl.GL_MODELVIEW);
            Gl.glPushMatrix();
            // load the view matrix
            MakeGLMatrix(ref viewMatrix, tempMatrix);
            Gl.glLoadMatrixf(tempMatrix);

            int i = 0;

            for( ; i < limit && i < lightList.Count; i++) {
                SetGLLight(i, lightList[i]);
                lights[i] = lightList[i];
            }

            for( ; i < numCurrentLights; i++) {
                SetGLLight(i, null);
                lights[i] = null;
            }

            numCurrentLights = (int)MathUtil.Min(limit, lightList.Count);

            SetLights();

            // restore the previous matrix
            Gl.glPopMatrix();
        }
Пример #34
0
		public override void UseLights( LightList lightList, int limit )
		{
			// save previous modelview matrix
			Gl.glMatrixMode( Gl.GL_MODELVIEW );
			Gl.glPushMatrix();
			// load the view matrix
			MakeGLMatrix( ref viewMatrix, _tempMatrix );
			Gl.glLoadMatrixf( _tempMatrix );

			var i = 0;
			for ( ; i < limit && i < lightList.Count; i++ )
			{
				SetGLLight( i, lightList[ i ] );
				lights[ i ] = lightList[ i ];
			}
            // Disable extra lights
			for ( ; i < _currentLights; i++ )
			{
				SetGLLight( i, null );
				lights[ i ] = null;
			}

			_currentLights = Utility.Min( limit, lightList.Count );

			SetLights();

			// restore the previous matrix
			Gl.glPopMatrix();
		}
Пример #35
0
 public void AddBinding(CompiledBinding binding)
 {
     bindings = bindings ?? new LightList <CompiledBinding>();
     bindings.Add(binding);
 }
Пример #36
0
		/// <summary>
		/// Tells the rendersystem to use the attached set of lights (and no others) 
		/// up to the number specified (this allows the same list to be used with different
		/// count limits).
		/// </summary>
		/// <param name="lightList">List of lights.</param>
		/// <param name="limit">Max number of lights that can be used from the list currently.</param>
		public override void UseLights(LightList lights, int limit)
		{
			var currentLightCount = lights.Count < limit ? lights.Count : limit;

			var lightList = new List<Light>();
#if AXIOM_FF_EMULATION
			_fixedFunctionState.GeneralFixedFunctionState.ResetLightTypeCounts();
			for ( int index = 0; index < currentLightCount; index++ )
			{
				Light light = lights[ index ];
				lightList.Add( light );
				_fixedFunctionState.GeneralFixedFunctionState.IncrementLightTypeCount( light.Type );
			}
			_ffProgramParameters.Lights = lightList;
#endif
		}
Пример #37
0
 public void AddSlot(CompiledSlot slot)
 {
     slots = slots ?? new LightList <CompiledSlot>();
     slots.Add(slot);
 }
Пример #38
0
			public VMDFormat(BinaryReader bin, string path, string clip_name)
			{
				// 読み込み失敗した場合はだいたいデータがない
				// 失敗しても読み込み続けることがあるので例外でキャッチして残りはnullにしておく
				try {
					this.clip_name = clip_name;
					this.header = new MMD.VMD.VMDFormat.Header(bin); read_count++;
					this.motion_list = new MMD.VMD.VMDFormat.MotionList(bin); read_count++;
					this.skin_list = new MMD.VMD.VMDFormat.SkinList(bin); read_count++;
					this.camera_list = new MMD.VMD.VMDFormat.CameraList(bin); read_count++;
					this.light_list = new MMD.VMD.VMDFormat.LightList(bin); read_count++;
					this.self_shadow_list = new MMD.VMD.VMDFormat.SelfShadowList(bin); read_count++;
				} catch (EndOfStreamException e) {
					Debug.Log(e.Message);
					if (read_count <= 0)
						this.header = null;
					if (read_count <= 1 || this.motion_list.motion_count <= 0)
						this.motion_list = null;
					if (read_count <= 2 || this.skin_list.skin_count <= 0)
						this.skin_list = null;
					if (read_count <= 3 || this.camera_list.camera_count <= 0)
						this.camera_list = null;
					if (read_count <= 4 || this.light_list.light_count <= 0)
						this.light_list = null;
					if (read_count <= 5 || this.self_shadow_list.self_shadow_count <= 0) 
						this.self_shadow_list = null;
				}
			}
Пример #39
0
 public override void OnChildrenChanged(LightList <AwesomeLayoutBox> childList)
 {
 }
Пример #40
0
		private void CheckShadowCasters( IList casters,
										 PlaneBoundedVolume nearClipVol,
										 Light light,
										 bool extrudeInSoftware,
										 bool finiteExtrude,
										 bool zfailAlgo,
										 Camera camera,
										 float extrudeDistance,
										 bool stencil2sided,
										 LightList tmpLightList )
		{
			int flags;
			for ( int i = 0; i < casters.Count; i++ )
			{
				ShadowCaster caster = (ShadowCaster)casters[ i ];

				if ( nearClipVol.Intersects( caster.GetWorldBoundingBox() ) )
				{
					// We have a zfail case, we must use zfail for all objects
					zfailAlgo = true;

					break;
				}
			}

			for ( int ci = 0; ci < casters.Count; ci++ )
			{
				ShadowCaster caster = (ShadowCaster)casters[ ci ];
				flags = 0;

				if ( light.Type != LightType.Directional )
				{
					extrudeDistance = caster.GetPointExtrusionDistance( light );
				}

				if ( !extrudeInSoftware && !finiteExtrude )
				{
					// hardware extrusion, to infinity (and beyond!)
					flags |= (int)ShadowRenderableFlags.ExtrudeToInfinity;
				}

				if ( zfailAlgo )
				{
					// We need to include the light and / or dark cap
					// But only if they will be visible
					if ( camera.IsObjectVisible( caster.GetLightCapBounds() ) )
					{
						flags |= (int)ShadowRenderableFlags.IncludeLightCap;
					}
				}

				// Dark cap (no dark cap for directional lights using
				// hardware extrusion to infinity)
				if ( !( ( flags & (int)ShadowRenderableFlags.ExtrudeToInfinity ) != 0 &&
						light.Type == LightType.Directional ) &&
					 camera.IsObjectVisible( caster.GetDarkCapBounds( light, extrudeDistance ) ) )
				{
					flags |= (int)ShadowRenderableFlags.IncludeDarkCap;
				}

				// get shadow renderables
				IEnumerator renderables = caster.GetShadowVolumeRenderableEnumerator(
					this.shadowTechnique, light, this.shadowIndexBuffer, extrudeInSoftware, extrudeDistance, flags );

				// If using one-sided stencil, render the first pass of all shadow
				// renderables before all the second passes
				for ( int i = 0; i < ( stencil2sided ? 1 : 2 ); i++ )
				{
					if ( i == 1 )
					{
						renderables = caster.GetLastShadowVolumeRenderableEnumerator();
					}

					while ( renderables.MoveNext() )
					{
						ShadowRenderable sr = (ShadowRenderable)renderables.Current;

						// omit hidden renderables
						if ( sr.IsVisible )
						{
							// render volume, including dark and (maybe) light caps
							this.RenderSingleShadowVolumeToStencil( sr,
																	zfailAlgo,
																	stencil2sided,
																	tmpLightList,
																	( i > 0 ) );

							// optionally render separate light cap
							if ( sr.IsLightCapSeperate
								 && ( ( flags & (int)ShadowRenderableFlags.IncludeLightCap ) ) > 0 )
							{
								// must always fail depth check
								this.targetRenderSystem.DepthBufferFunction = CompareFunction.AlwaysFail;

								Debug.Assert( sr.LightCapRenderable != null,
											  "Shadow renderable is missing a separate light cap renderable!" );

								this.RenderSingleShadowVolumeToStencil( sr.LightCapRenderable,
																		zfailAlgo,
																		stencil2sided,
																		tmpLightList,
																		( i > 0 ) );
								// reset depth function
                                this.targetRenderSystem.DepthBufferFunction = CompareFunction.Less;
							}
						}
					}
				}
			}
		}
Пример #41
0
 public void SetElements(LightList <UIElement> elements)
 {
     this.elements.AddRange(elements);
     size = elements.size;
 }
Пример #42
0
		/// <summary>
		///		Internal utility method for rendering a single object.
		/// </summary>
		/// <param name="renderable">The renderable to issue to the pipeline.</param>
		/// <param name="pass">The pass which is being used.</param>
		/// <param name="doLightIteration">If true, this method will issue the renderable to
		/// the pipeline possibly multiple times, if the pass indicates it should be
		/// done once per light.</param>
		/// <param name="manualLightList">Only applicable if 'doLightIteration' is false, this
		/// method allows you to pass in a previously determined set of lights
		/// which will be used for a single render of this object.</param>
		protected virtual void RenderSingleObject( IRenderable renderable,
												   Pass pass,
												   bool doLightIteration,
												   LightList manualLightList )
		{
			ushort numMatrices = 0;

			// grab the current scene detail level
			PolygonMode camPolyMode = this.cameraInProgress.PolygonMode;

			// get the world matrices and the count
			renderable.GetWorldTransforms( this.xform );
			numMatrices = renderable.NumWorldTransforms;

			// set the world matrices in the render system
			if ( numMatrices > 1 )
			{
				this.targetRenderSystem.SetWorldMatrices( this.xform, numMatrices );
			}
			else
			{
				this.targetRenderSystem.WorldMatrix = this.xform[ 0 ];
			}

			// issue view/projection changes (if any)
			this.UseRenderableViewProjection( renderable );

			if ( !this.suppressRenderStateChanges )
			{
				bool passSurfaceAndLightParams = true;
				if ( pass.IsProgrammable )
				{
					// Tell auto params object about the renderable change
					this.autoParamDataSource.Renderable = renderable;
					pass.UpdateAutoParamsNoLights( this.autoParamDataSource );
					if ( pass.HasVertexProgram )
					{
						passSurfaceAndLightParams = pass.VertexProgram.PassSurfaceAndLightStates;
					}
				}

				// issue texture units that depend on updated view matrix
				// reflective env mapping is one case
				for ( int i = 0; i < pass.TextureUnitStageCount; i++ )
				{
					TextureUnitState texUnit = pass.GetTextureUnitState( i );

					if ( texUnit.HasViewRelativeTexCoordGen )
					{
					    targetRenderSystem.SetTextureUnitSettings( i, texUnit );
					    //this.targetRenderSystem.SetTextureUnit( i, texUnit, !pass.HasFragmentProgram );
					}
				}

				// Normalize normals
				bool thisNormalize = renderable.NormalizeNormals;

				if ( thisNormalize != normalizeNormals )
				{
					this.targetRenderSystem.NormalizeNormals = thisNormalize;
					normalizeNormals = thisNormalize;
				}

				// Set up the solid / wireframe override
				PolygonMode requestedMode = pass.PolygonMode;
				if ( renderable.PolygonModeOverrideable == true )
				{
					// check camera detial only when render detail is overridable
					if ( requestedMode > camPolyMode )
					{
						// only downgrade detail; if cam says wireframe we don't go up to solid
						requestedMode = camPolyMode;
					}
				}

				if ( requestedMode != this.lastPolyMode )
				{
					this.targetRenderSystem.PolygonMode = requestedMode;
					this.lastPolyMode = requestedMode;
				}

				// TODO: Add ClipPlanes to RenderSystem.cs
				// This is removed in OGRE 1.6.0... no need to port - J. Price
				//targetRenderSystem.ClipPlanes = renderable.ClipPlanes;

				// get the renderables render operation
				op = renderable.RenderOperation;
				// TODO: Add srcRenderable to RenderOperation.cs
				//op.srcRenderable = renderable;

				if ( doLightIteration )
				{
					// Here's where we issue the rendering operation to the render system
					// Note that we may do this once per light, therefore it's in a loop
					// and the light parameters are updated once per traversal through the
					// loop
					LightList rendLightList = renderable.Lights;
					bool iteratePerLight = pass.IteratePerLight;
					int numIterations = iteratePerLight ? rendLightList.Count : 1;
					LightList lightListToUse = null;

					for ( int i = 0; i < numIterations; i++ )
					{
						// determine light list to use
						if ( iteratePerLight )
						{
							localLightList.Clear();

							// check whether we need to filter this one out
							if ( pass.RunOnlyOncePerLightType && pass.OnlyLightType != rendLightList[ i ].Type )
							{
								// skip this one
								continue;
							}

							localLightList.Add( rendLightList[ i ] );
							lightListToUse = localLightList;
						}
						else
						{
							// use complete light list
							lightListToUse = rendLightList;
						}

						if ( pass.IsProgrammable )
						{
							// Update any automatic gpu params for lights
							// Other bits of information will have to be looked up
							this.autoParamDataSource.SetCurrentLightList( lightListToUse );
							pass.UpdateAutoParamsLightsOnly( this.autoParamDataSource );

						    UpdateGpuProgramParameters( pass );
						}

						// Do we need to update light states?
						// Only do this if fixed-function vertex lighting applies
						if ( pass.LightingEnabled && passSurfaceAndLightParams )
						{
							this.targetRenderSystem.UseLights( lightListToUse, pass.MaxSimultaneousLights );
						}
                        this.targetRenderSystem.CurrentPassIterationCount = pass.IterationCount;
						// issue the render op
						this.targetRenderSystem.Render( op );
					} // iterate per light
				}
				else
				{
					// do we need to update GPU program parameters?
					if ( pass.IsProgrammable )
					{
						// do we have a manual light list
						if ( manualLightList != null )
						{
							// Update any automatic gpu params for lights
							// Other bits of information will have to be looked up
							this.autoParamDataSource.SetCurrentLightList( manualLightList );
							pass.UpdateAutoParamsLightsOnly( this.autoParamDataSource );
						}

					    UpdateGpuProgramParameters( pass );
					}

					// Use manual lights if present, and not using vertex programs
					if ( manualLightList != null && pass.LightingEnabled && passSurfaceAndLightParams )
					{
						this.targetRenderSystem.UseLights( manualLightList, pass.MaxSimultaneousLights );
					}
                    this.targetRenderSystem.CurrentPassIterationCount = pass.IterationCount;
					// issue the render op
					this.targetRenderSystem.Render( op );
				}
			}
			else
			{
				// suppressRenderStateChanges
				// Just render
                this.targetRenderSystem.CurrentPassIterationCount = 1;
				this.targetRenderSystem.Render( op );
			}

			// Reset view / projection changes if any
			this.ResetViewProjectionMode();
		}
Пример #43
0
 public StyleStateIndex(StyleState styleState)
 {
     this.styleState = styleState;
     this.elements   = new LightList <UIElement>();
 }
Пример #44
0
		/// <summary>
		///		Renders a set of transparent objects.
		/// </summary>
		protected virtual void RenderTransparentObjects( List<RenderablePass> list, bool doLightIteration,
														 LightList manualLightList )
		{
			// ----- TRANSPARENT LOOP -----
			// This time we render by Z, not by material
			// The transparent objects set needs to be ordered first
			for ( int i = 0; i < list.Count; i++ )
			{
				RenderablePass rp = (RenderablePass)list[ i ];

				// set the pass first
				this.SetPass( rp.pass );

				// render the transparent object
				this.RenderSingleObject( rp.renderable,
										 rp.pass,
										 doLightIteration,
										 manualLightList );
			}
		}
Пример #45
0
 public void AddVariableNode(VariableDefinitionNode node)
 {
     variableNodes = variableNodes ?? new LightList <VariableDefinitionNode>(4);
     variableNodes.Add(node);
 }
Пример #46
0
		/// <summary>
		///		Render a group with the added complexity of additive texture shadows.
		/// </summary>
		/// <param name="group">Render queue group.</param>
		private void RenderAdditiveTextureShadowedQueueGroupObjects( RenderQueueGroup group )
		{
			LightList tempLightList = new LightList();
			foreach ( RenderPriorityGroup priorityGroup in group.PriorityGroups.Values )
			{
				// Sort the queue first
				priorityGroup.Sort( this.cameraInProgress );

				// Clear light list
				tempLightList.Clear();

				// Render all the ambient passes first, no light iteration, no lights
				this.RenderSolidObjects( priorityGroup.solidPasses, false, tempLightList );
				// Also render any objects which have receive shadows disabled
				this.renderingNoShadowQueue = true;
				this.RenderSolidObjects( priorityGroup.solidPassesNoShadow, true );
				this.renderingNoShadowQueue = false;

				// only perform this next part if we're in the 'normal' render stage, to avoid
				// doing it during the render to texture
				if ( this.illuminationStage == IlluminationRenderStage.None )
				{
					// Iterate over lights, render masked
					int sti = 0;
					foreach ( Light light in this.lightsAffectingFrustum )
					{
						// Set light state
						if ( light.CastShadows && sti < this.shadowTextures.Count )
						{
							Texture shadowTex = this.shadowTextures[ sti ];
							// Get camera for current shadow texture
							Camera camera = shadowTex.GetBuffer().GetRenderTarget().GetViewport( 0 ).Camera;
							// Hook up receiver texture
							Pass targetPass = this.shadowTextureCustomReceiverPass != null
												  ? this.shadowTextureCustomReceiverPass
												  : this.shadowReceiverPass;
							targetPass.GetTextureUnitState( 0 ).SetTextureName( shadowTex.Name );
							// Hook up projection frustum
							targetPass.GetTextureUnitState( 0 ).SetProjectiveTexturing( true, camera );
							this.autoParamDataSource.TextureProjector = camera;
							// Remove any spot fader layer
							if ( targetPass.TextureUnitStageCount > 1 &&
								 targetPass.GetTextureUnitState( 1 ).TextureName == "spot_shadow_fade.png" )
							{
								// remove spot fader layer (should only be there if
								// we previously used modulative shadows)
								targetPass.RemoveTextureUnitState( 1 );
							}
							// Set lighting / blending modes
							targetPass.SetSceneBlending( SceneBlendFactor.One, SceneBlendFactor.One );
							targetPass.LightingEnabled = true;
							targetPass.Load();
							// increment shadow texture since used
							++sti;
							this.illuminationStage = IlluminationRenderStage.RenderReceiverPass;
						}
						else
						{
							this.illuminationStage = IlluminationRenderStage.None;
						}

						// render lighting passes for this light
						tempLightList.Clear();
						tempLightList.Add( light );

						this.RenderSolidObjects( priorityGroup.solidPassesDiffuseSpecular, false, tempLightList );
					} // for each light
					this.illuminationStage = IlluminationRenderStage.None;

					// Now render decal passes, no need to set lights as lighting will be disabled
					this.RenderSolidObjects( priorityGroup.solidPassesDecal, false );
				}
			} // for each priority

			foreach ( RenderPriorityGroup priorityGroup in group.PriorityGroups.Values )
			{
				// Do transparents
				this.RenderTransparentObjects( priorityGroup.transparentPasses, true );
			} // for each priority
		}
Пример #47
0
 public void AddOptionNode(AnimationOptionNode optionNode)
 {
     optionNodes = optionNodes ?? new LightList <AnimationOptionNode>(4);
     optionNodes.Add(optionNode);
 }
Пример #48
0
		/// <summary>
		///		Populate a light list with an ordered set of the lights which are closest
		/// </summary>
		/// <remarks>
		///		<p>
		///		Note that since directional lights have no position, they are always considered
		///		closer than any point lights and as such will always take precedence.
		///		</p>
		///		<p>
		///		Subclasses of the default SceneManager may wish to take into account other issues
		///		such as possible visibility of the light if that information is included in their
		///		data structures. This basic scenemanager simply orders by distance, eliminating
		///		those lights which are out of range.
		///		</p>
		///		<p>
		///		The number of items in the list max exceed the maximum number of lights supported
		///		by the renderer, but the extraneous ones will never be used. In fact the limit will
		///		be imposed by Pass::getMaxSimultaneousLights.
		///		</p>
		/// </remarks>
		/// <param name="position">The position at which to evaluate the list of lights</param>
		/// <param name="radius">The bounding radius to test</param>
		/// <param name="destList">List to be populated with ordered set of lights; will be cleared by this method before population.</param>
		public virtual void PopulateLightList( Vector3 position, float radius, LightList destList )
		{
			// Really basic trawl of the lights, then sort
			// Subclasses could do something smarter
			destList.Clear();
			float squaredRadius = radius * radius;

			MovableObjectCollection lightList = this.GetMovableObjectCollection( LightFactory.TypeName );

			// loop through the scene lights an add ones in range
			foreach ( Light light in lightList.Values )
			{
				if ( light.IsVisible )
				{
					if ( light.Type == LightType.Directional )
					{
						// no distance
						light.tempSquaredDist = 0.0f;
						destList.Add( light );
					}
					else
					{
						light.tempSquaredDist = ( light.DerivedPosition - position ).LengthSquared;
						light.tempSquaredDist -= squaredRadius;
						// only add in-range lights
						float range = light.AttenuationRange;
						if ( light.tempSquaredDist <= ( range * range ) )
						{
							destList.Add( light );
						}
					}
				} // if
			} // for

			// Sort Destination light list.
			// TODO: Not needed yet since the current LightList is a sorted list under the hood already
			//destList.Sort();
		}
        /// <summary>
        ///		Overriden from SceneManager.
        /// </summary>
        protected override void RenderSingleObject(IRenderable renderable, Pass pass, 
			bool doLightIteration, LightList manualLightList)
        {
            if (renderable is BspGeometry)
            {
                // Render static level geometry
                if (doLightIteration)
                {
                    // render all geometry without lights first
                    RenderStaticGeometry();

                    // render geometry affected by each visible light
                    for (int i = 0; i < lightsAffectingFrustum.Count; i++)
                    {
                        int index;

                        // find the index of the light
                        for (index = 0; index < lightList.Count; index++)
                            if (lightList[index] == lightsAffectingFrustum[i]) break;

                        if (index < lightList.Count)
                        {
                            RenderTextureLighting(index);
                        }
                    }
                }
                else
                {
                    if (manualLightList.Count == 0)
                    {
                        if (illuminationStage == IlluminationRenderStage.RenderModulativePass)
                        {
                            // texture shadows
                            RenderTextureShadowOnGeometry();
                        }
                        else
                        {
                            // ambient stencil pass, render geometry without lights
                            RenderStaticGeometry();
                        }
                    }
                    else
                    {
                        // render only geometry affected by the provided light
                        for (int i = 0; i < manualLightList.Count; i++)
                        {
                            int index;

                            // find the index of the light
                            for (index = 0; index < lightList.Count; index++)
                                if (lightList[index] == manualLightList[i]) break;

                            if (index < lightList.Count)
                            {
                                RenderTextureLighting(index);
                            }
                        }
                    }
                }
            }
            else
            {
                base.RenderSingleObject(renderable, pass, doLightIteration, manualLightList);
            }
        }