Exemple #1
0
 protected static void QueueShaderResourceUpdate(Shader shader, ShaderResourcePackage resourcePackage)
 {
     Assure.NotNull(shader);
     Assure.False(shader.IsDisposed, "Shader was disposed.");
     Assure.NotNull(resourcePackage);
     shader.RCQUpdateResources(ThreadLocalRCQ, resourcePackage);
 }
        public static unsafe RenderCommand SetRenderTargets(DepthStencilView dsv, params RenderTargetView[] rtvArr)
        {
            Assure.NotNull(dsv);
            Assure.False(dsv.ResourceOrViewDisposed, "Depth Stencil View or its resource was disposed.");
            Assure.NotNull(rtvArr);
            Assure.None(rtvArr, rtv => rtv == null, "One or more elements in the render target view array were null.");
            Assure.None(
                rtvArr,
                rtv => rtv.ResourceOrViewDisposed,
                "One or more elements in the render target view array (or their resources) were disposed."
                );
            Assure.LessThanOrEqualTo(rtvArr.Length, MAX_RENDER_TARGETS, "Maximum of " + MAX_RENDER_TARGETS + " render targets permitted.");
            RenderTargetViewHandle *rtvArrPtr = (RenderTargetViewHandle *)AllocAndZeroTemp((uint)(rtvArr.Length * sizeof(RenderTargetViewHandle)));

            for (int i = 0; i < rtvArr.Length; i++)
            {
                rtvArrPtr[i] = rtvArr[i].ResourceViewHandle;
            }

            return(new RenderCommand(
                       RenderCommandInstruction.SetRenderTargets,
                       (IntPtr)rtvArrPtr,
                       (IntPtr)(ResourceViewHandle)dsv.ResourceViewHandle,
                       (uint)rtvArr.Length
                       ));
        }
        protected void CopyTo(BaseResource dest, SubresourceBox srcBox, uint srcSubresourceIndex, uint dstSubresourceIndex,
                              uint dstX, uint dstY, uint dstZ)
        {
            Assure.NotNull(dest);
            Assure.False(this == dest && srcSubresourceIndex == dstSubresourceIndex, "Can not copy to/from same subresource.");
            dest.ThrowIfCannotBeCopyDestination();

            lock (InstanceMutationLock) {
                if (IsDisposed)
                {
                    Logger.Warn("Attempted copy manipulation from disposed resource of type: " + GetType().Name);
                    return;
                }
                lock (dest.InstanceMutationLock) {
                    if (IsDisposed)
                    {
                        Logger.Warn("Attempted copy manipulation to disposed resource of type: " + GetType().Name);
                        return;
                    }
                    InteropUtils.CallNative(
                        NativeMethods.ResourceFactory_CopySubresourceRegion,
                        RenderingModule.DeviceContext,
                        ResourceHandle,
                        srcSubresourceIndex,
                        (IntPtr)(&srcBox),
                        dest.ResourceHandle,
                        dstSubresourceIndex,
                        dstX,
                        dstY,
                        dstZ
                        ).ThrowOnFailure();
                }
            }
        }
Exemple #4
0
        public static unsafe RenderCommand SetShaderVertexBuffers(VertexShader shader, Dictionary <VertexInputBinding, IVertexBuffer> values)
        {
            Assure.NotNull(shader);
            Assure.False(shader.IsDisposed, "Shader was disposed.");
            Assure.NotNull(values);
            Assure.None(values.Keys, key => key == null, "One or more keys in the given dictionary of values was null.");
            Assure.None(values.Values, val => val != null && val.IsDisposed, "One or more values in the given dictionary of values was disposed.");
            IntPtr *resourceHandleArrayPtr = (IntPtr *)AllocAndZeroTemp(shader.NumInputSlots * (uint)sizeof(IntPtr));
            uint *  bufferStrideArrPtr     = (uint *)AllocAndZeroTemp(shader.NumInputSlots * sizeof(uint));

            foreach (KeyValuePair <VertexInputBinding, IVertexBuffer> kvp in values)
            {
                if (kvp.Value == null)
                {
                    continue;                                    // Legitimate: If we want to set a bind to null, this is how it's done
                }
                resourceHandleArrayPtr[kvp.Key.SlotIndex] = (IntPtr)kvp.Value.ResourceHandle;
                bufferStrideArrPtr[kvp.Key.SlotIndex]     = kvp.Value.ElementSizeBytes;
            }

            return(new RenderCommand(
                       RenderCommandInstruction.SetVertexBuffers,
                       (IntPtr)resourceHandleArrayPtr,
                       (IntPtr)bufferStrideArrPtr,
                       shader.NumInputSlots
                       ));
        }
Exemple #5
0
        /// <summary>
        /// Constructs a new material.
        /// </summary>
        /// <param name="name">The name of the material. Must not be null or whitespace.</param>
        /// <param name="shader">The fragment shader used to draw objects rendered with this material.</param>
        public Material(string name, FragmentShader shader)
        {
            Assure.False(name.IsNullOrEmpty(), "Invalid material name.");
            Assure.NotNull(shader);
            Assure.False(shader.IsDisposed, "Shader must not be disposed.");
            Name   = name;
            Shader = shader;
            lock (staticMutationLock) {
                for (uint i = 0; i < activeMaterials.Length; ++i)
                {
                    if (activeMaterials[i] == null)
                    {
                        Index = i;
                        goto slotFound;
                    }
                }
                Material[] newMatArray = new Material[activeMaterials.Length * 2];
                Array.Copy(activeMaterials, newMatArray, activeMaterials.Length);
                Index           = (uint)activeMaterials.Length;
                activeMaterials = newMatArray;
                slotFound : activeMaterials[Index] = this;

                shaderMaterialMap.GetOrCreate(shader, _ => new List <Material>()).Add(this);
            }
        }
        /// <summary>
        /// Creates an array of <see cref="Texture2D{TTexel}"/>s; encapsulated as a <see cref="Texture2DArray{TTexel}"/> object.
        /// By grouping textures that are used together frequently in to an array, you can gain a performance improvement.
        /// You can not create an array of textures with usage '<see cref="ResourceUsage.DiscardWrite"/>'.
        /// </summary>
        /// <param name="numTextures">The number of textures in the array. Must not be zero.</param>
        /// <returns>A new <see cref="Texture2DArray{TTexel}"/>.</returns>
        public Texture2DArray <TTexel> CreateArray(uint numTextures)
        {
            Assure.False(Usage == ResourceUsage.DiscardWrite, "Can not create an array of discard-write textures.");

            Texture2DArray <TTexel> result = new Texture2DArray <TTexel>(
                CreateTexture2D(numTextures, InitialData),
                Usage,
                TextureUtils.GetSize(texelSizeBytes, mipAllocation, width, height) * numTextures,
                permittedBindings,
                numTextures,
                mipGenerationTarget,
                dynamicDetail,
                width,
                height,
                texelSizeBytes,
                mipAllocation,
                numMips,
                multisampling
                );

            if (dynamicDetail)
            {
                RenderingModule.DynamicDetailTextures.Value.Add(new WeakReference <IResource>(result));
            }
            return(result);
        }
Exemple #7
0
        public ModelInstanceHandle CreateInstance(ModelHandle modelHandle, Material material, Transform initialTransform)
        {
            uint modelIndex = modelHandle.ModelIndex;

            Assure.NotNull(material);
            Assure.False(material.IsDisposed, "Given material was disposed!");
            return(GeometryCache.GetCacheByID(modelHandle.GeoCacheID).AllocInstance(modelIndex, OwningLayer.Index, material.Index, initialTransform));
        }
Exemple #8
0
        public static RenderCommand DiscardWriteShaderConstantBuffer(ConstantBufferBinding binding, IntPtr valuePtr)
        {
            Assure.NotNull(binding);
            Assure.NotEqual(valuePtr, IntPtr.Zero, "valuePtr must not be IntPtr.Zero!");
            Assure.False(binding.IsDisposed || binding.GetBoundResource().IsDisposed, "Given binding or its resource was disposed.");
            IntPtr cbufferValPtr = AllocAndZeroTemp(binding.BufferSizeBytes);

            UnsafeUtils.MemCopy(valuePtr, cbufferValPtr, binding.BufferSizeBytes);
            return(new RenderCommand(RenderCommandInstruction.CBDiscardWrite, (IntPtr)binding.GetBoundResource().ResourceHandle, cbufferValPtr, binding.BufferSizeBytes));
        }
 public EggCameraBoom(EggEntity egg, Camera camera, float cameraHeight, float cameraDistance)
 {
     Assure.NotNull(egg);
     Assure.NotNull(camera);
     Assure.False(egg.IsDisposed);
     Assure.False(camera.IsDisposed);
     Egg                 = egg;
     Camera              = camera;
     this.cameraHeight   = cameraHeight;
     this.cameraDistance = cameraDistance;
 }
 public void SetModelInstance(SceneLayer layer, ModelHandle modelHandle, Material material)
 {
     lock (InstanceMutationLock) {
         Assure.False(isDisposed);
         if (modelInstance != null)
         {
             modelInstance.Value.Dispose();
         }
         modelInstance = layer.CreateModelInstance(modelHandle, material, transform);
     }
 }
        /// <summary>
        /// Creates a new <see cref="Buffer{TElement}"/> with the supplied builder parameters.
        /// </summary>
        /// <remarks>
        /// In debug mode, this method will check a large number of <see cref="Assure">assurances</see>
        /// on the builder parameters before creating the resource.
        /// </remarks>
        /// <returns>A new <see cref="Buffer{TElement}"/>.</returns>
        public unsafe override Buffer <TElement> Create()
        {
            Assure.True(Usage != ResourceUsage.Immutable || InitialData != null, "You must supply initial data to an immutable resource.");
            Assure.False(
                (Usage == ResourceUsage.Immutable || Usage == ResourceUsage.DiscardWrite) && permittedBindings == GPUBindings.None,
                "An immutable or discard-write resource with no permitted bindings is useless."
                );
            Assure.False(
                Usage.GetUsage() == 0x3 && permittedBindings != GPUBindings.None,
                "Staging resources can not be bound to the pipeline."
                );
            Assure.GreaterThan(length, 0U, "Can not create a buffer with 0 elements.");

            InteropBool isStructured   = (BaseResource.GetFormatForType(typeof(TElement)) == ResourceFormat.Unknown);
            InteropBool allowRawAccess =
                !isStructured &&
                (int)(permittedBindings & (GPUBindings.WritableShaderResource | GPUBindings.ReadableShaderResource)) != 0;

            GCHandle?pinnedArrayHandle = null;
            IntPtr   initialDataPtr    = IntPtr.Zero;

            try {
                int elementSizeBytes = UnsafeUtils.SizeOf <TElement>();

                if (InitialData != null)
                {
                    pinnedArrayHandle = GCHandle.Alloc(InitialData.Value.ContainingArray, GCHandleType.Pinned);
                    initialDataPtr    = pinnedArrayHandle.Value.AddrOfPinnedObject() + (elementSizeBytes * (int)InitialData.Value.Offset);
                }

                BufferResourceHandle outResourceHandle;
                InteropUtils.CallNative(NativeMethods.ResourceFactory_CreateBuffer,
                                        RenderingModule.Device,
                                        (uint)elementSizeBytes,
                                        length,
                                        Usage.GetUsage(),
                                        Usage.GetCPUUsage(),
                                        (PipelineBindings)permittedBindings,
                                        isStructured,
                                        allowRawAccess,
                                        initialDataPtr,
                                        (IntPtr)(&outResourceHandle)
                                        ).ThrowOnFailure();

                return(new Buffer <TElement>(outResourceHandle, Usage, (uint)elementSizeBytes, length, permittedBindings, isStructured));
            }
            finally {
                if (pinnedArrayHandle != null)
                {
                    pinnedArrayHandle.Value.Free();
                }
            }
        }
Exemple #12
0
 /// <summary>
 /// Sets the resource for the given <paramref name="binding"/>.
 /// </summary>
 /// <typeparam name="TValue">The resource type specified by the supplied <paramref name="binding"/>.</typeparam>
 /// <param name="binding">The <see cref="IShaderResourceBinding"/> to pair a resource with.</param>
 /// <param name="value">The resource to pair to the <paramref name="binding"/>.</param>
 public void SetValue <TValue>(BaseShaderResourceBinding <TValue> binding, TValue value) where TValue : class
 {
     if (binding is ConstantBufferBinding)
     {
         SetValue((ConstantBufferBinding)(object)binding, (IntPtr)(object)value);
         return;
     }
     lock (instanceMutationLock) {
         Assure.False(binding is ConstantBufferBinding, "Can not set value for Constant Buffer Bindings.");
         this.bindings[binding] = value;
     }
 }
 public virtual void Ground(GeometryEntity e)
 {
     Assure.NotNull(e);
     Assure.False(e.IsDisposed);
     lock (InstanceMutationLock) {
         Assure.False(IsDisposed);
         initialTransform          = transform;
         groundingEntity           = e;
         groundingInitialTransform = (e is PresetMovementEntity ? ((PresetMovementEntity)e).MovementSteps[0].Transform : e.Transform);
         groundingToThisConstraint = initialTransform.Translation - groundingInitialTransform.Translation;
     }
     SetGravity(Vector3.ZERO);
 }
 public void AddLight(Light light)
 {
     Assure.NotNull(light);
     lock (InstanceMutationLock) {
         Assure.False(addedLights.Contains(light), "Light is already added!");
         if (addedLights.Count == MAX_DYNAMIC_LIGHTS)
         {
             //Logger.Warn("Tried to add a light when max lights already exceeded.");
             return;
         }
         addedLights.Add(light);
     }
 }
Exemple #15
0
        public FontString AddString(SceneLayer sceneLayer, SceneViewport viewport,
                                    ViewportAnchoring anchoring, Vector2 anchorOffset, Vector2 scale)
        {
            lock (instanceMutationLock) {
                Assure.NotNull(sceneLayer);
                Assure.False(sceneLayer.IsDisposed);
                Assure.NotNull(viewport);
                Assure.False(viewport.IsDisposed);
                if (isDisposed)
                {
                    throw new ObjectDisposedException(Name);
                }

                return(new FontString(this, sceneLayer, viewport, anchoring, anchorOffset, scale));
            }
        }
Exemple #16
0
        public static unsafe RenderCommand SetShaderConstantBuffers(Shader shader)
        {
            Assure.NotNull(shader);
            Assure.False(shader.IsDisposed, "Shader was disposed.");
            IntPtr *resourceHandleArrayPtr = (IntPtr *)AllocAndZeroTemp(shader.NumConstantBufferSlots * (uint)sizeof(IntPtr));

            for (int i = 0; i < shader.ConstantBufferBindings.Length; i++)
            {
                IConstantBuffer boundResource = shader.ConstantBufferBindings[i].GetBoundResource();
                if (boundResource == null)
                {
                    continue;
                }
                resourceHandleArrayPtr[shader.ConstantBufferBindings[i].SlotIndex] = (IntPtr)boundResource.ResourceHandle;
            }
            return(new RenderCommand(shader.SetConstantBuffersInstruction, (IntPtr)resourceHandleArrayPtr, shader.NumConstantBufferSlots, 0U));
        }
Exemple #17
0
        public static unsafe RenderCommand SetShaderTextureSamplers(Shader shader, FastClearList <KVP <TextureSamplerBinding, TextureSampler> > values)
        {
            Assure.NotNull(shader);
            Assure.False(shader.IsDisposed, "Shader was disposed.");
            Assure.NotNull(values);
            IntPtr *resourceHandleArrayPtr = (IntPtr *)AllocAndZeroTemp(shader.NumTextureSamplerSlots * (uint)sizeof(IntPtr));

            for (int i = 0; i < values.Count; ++i)
            {
                var kvp = values[i];
                if (kvp.Value == null)
                {
                    continue;                                    // Legitimate: If we want to set a bind to null, this is how it's done
                }
                resourceHandleArrayPtr[kvp.Key.SlotIndex] = (IntPtr)kvp.Value.ResourceHandle;
            }
            return(new RenderCommand(shader.SetTextureSamplersInstruction, (IntPtr)resourceHandleArrayPtr, shader.NumTextureSamplerSlots, 0U));
        }
Exemple #18
0
        internal virtual void RCQUpdateResources(RenderCommandQueue commandQueue, ShaderResourcePackage shaderResources)
        {
            for (int i = 0; i < ConstantBufferBindings.Length; i++)
            {
                commandQueue.QueueCommand(RenderCommand.DiscardWriteShaderConstantBuffer(
                                              ConstantBufferBindings[i], shaderResources.GetValue(ConstantBufferBindings[i])
                                              ));
            }

            if (TextureSamplerBindings.Length > 0)
            {
                if (texSamplerValueDict == null)
                {
                    texSamplerValueDict = new FastClearList <KVP <TextureSamplerBinding, TextureSampler> >();
                }
                texSamplerValueDict.Clear();
                for (int i = 0; i < TextureSamplerBindings.Length; ++i)
                {
                    var tsb = TextureSamplerBindings[i];
                    texSamplerValueDict.Add(new KVP <TextureSamplerBinding, TextureSampler>(tsb, shaderResources.GetValue(tsb)));
                }
                commandQueue.QueueCommand(RenderCommand.SetShaderTextureSamplers(this, texSamplerValueDict));
            }

            if (ResourceViewBindings.Length > 0)
            {
                if (resViewValueDict == null)
                {
                    resViewValueDict = new FastClearList <KVP <ResourceViewBinding, IResourceView> >();
                }
                resViewValueDict.Clear();
                for (int i = 0; i < ResourceViewBindings.Length; ++i)
                {
                    var rvb = ResourceViewBindings[i];
                    resViewValueDict.Add(new KVP <ResourceViewBinding, IResourceView>(rvb, shaderResources.GetValue(rvb)));
                    Assure.False(
                        ((BaseResourceView)shaderResources.GetValue(ResourceViewBindings[i])) != null &&
                        ((BaseResourceView)shaderResources.GetValue(ResourceViewBindings[i])).Resource.PermittedBindings == GPUBindings.None,
                        "Underlying resource has no permitted GPU bindings."
                        );
                }
                commandQueue.QueueCommand(RenderCommand.SetShaderResourceViews(this, resViewValueDict));
            }
        }
        internal static unsafe RenderCommand SetRenderTargets(DepthStencilViewHandle dsv, RenderTargetView rtv)
        {
            Assure.NotNull(rtv);
            Assure.False(
                rtv.ResourceOrViewDisposed,
                "One or more elements in the render target view array (or their resources) were disposed."
                );
            RenderTargetViewHandle *rtvArrPtr = (RenderTargetViewHandle *)AllocAndZeroTemp((uint)(sizeof(RenderTargetViewHandle)));

            *rtvArrPtr = rtv.ResourceViewHandle;


            return(new RenderCommand(
                       RenderCommandInstruction.SetRenderTargets,
                       (IntPtr)rtvArrPtr,
                       (IntPtr)(ResourceViewHandle)dsv,
                       1U
                       ));
        }
Exemple #20
0
        internal virtual void RCQUpdateResources(RenderCommandQueue commandQueue)
        {
            for (int i = 0; i < ConstantBufferBindings.Length; i++)
            {
                commandQueue.QueueCommand(RenderCommand.DiscardWriteShaderConstantBuffer(
                                              ConstantBufferBindings[i], ConstantBufferBindings[i].CurValuePtr
                                              ));
            }

            if (TextureSamplerBindings.Length > 0)
            {
                if (texSamplerValueDict == null)
                {
                    texSamplerValueDict = new FastClearList <KVP <TextureSamplerBinding, TextureSampler> >();
                }
                texSamplerValueDict.Clear();
                for (int i = 0; i < TextureSamplerBindings.Length; ++i)
                {
                    texSamplerValueDict.Add(new KVP <TextureSamplerBinding, TextureSampler>(TextureSamplerBindings[i], TextureSamplerBindings[i].GetBoundResource()));
                }
                commandQueue.QueueCommand(RenderCommand.SetShaderTextureSamplers(this, texSamplerValueDict));
            }

            if (ResourceViewBindings.Length > 0)
            {
                if (resViewValueDict == null)
                {
                    resViewValueDict = new FastClearList <KVP <ResourceViewBinding, IResourceView> >();
                }
                resViewValueDict.Clear();
                for (int i = 0; i < ResourceViewBindings.Length; ++i)
                {
                    resViewValueDict.Add(new KVP <ResourceViewBinding, IResourceView>(ResourceViewBindings[i], ResourceViewBindings[i].GetBoundResourceAsBaseResourceView()));
                    Assure.False(ResourceViewBindings[i].GetBoundResourceAsBaseResourceView().Resource.PermittedBindings == GPUBindings.None, "Underlying resource has no permitted GPU bindings.");
                }
                commandQueue.QueueCommand(RenderCommand.SetShaderResourceViews(this, resViewValueDict));
            }
        }
        internal static unsafe RenderCommand SetRenderTargets(Window blackOut, DepthStencilView dsv, params RenderTargetView[] rtvArr)
        {
            Assure.NotNull(rtvArr);
            Assure.None(rtvArr, rtv => rtv == null, "One or more elements in the render target view array were null.");
            Assure.None(
                rtvArr,
                rtv => rtv.ResourceOrViewDisposed,
                "One or more elements in the render target view array (or their resources) were disposed."
                );
            Assure.LessThanOrEqualTo(rtvArr.Length, MAX_RENDER_TARGETS, "Maximum of " + MAX_RENDER_TARGETS + " render targets permitted.");
            Assure.NotNull(dsv);
            Assure.False(dsv.IsDisposed);
            RenderTargetViewHandle *rtvArrPtr = (RenderTargetViewHandle *)AllocAndZeroTemp((uint)((rtvArr.Length + 1) * sizeof(RenderTargetViewHandle)));

            RenderTargetViewHandle outRTV;
            DepthStencilViewHandle outDSV;

            bool windowStillOpen = blackOut.GetWindowRTVAndDSV(out outRTV, out outDSV);

            if (!windowStillOpen)
            {
                return(new RenderCommand(RenderCommandInstruction.NoOperation));
            }

            rtvArrPtr[0] = outRTV;
            for (int i = 1; i < rtvArr.Length + 1; i++)
            {
                rtvArrPtr[i] = rtvArr[i - 1].ResourceViewHandle;
            }

            return(new RenderCommand(
                       RenderCommandInstruction.SetRenderTargets,
                       (IntPtr)rtvArrPtr,
                       (IntPtr)(ResourceViewHandle)dsv.ResourceViewHandle,
                       (uint)rtvArr.Length + 1U
                       ));
        }
 public static RenderCommand SetShader(Shader shader)
 {
     Assure.NotNull(shader);
     Assure.False(shader.IsDisposed, "Shader was disposed.");
     return(new RenderCommand(shader.SetShaderInstruction, (IntPtr)shader.Handle));
 }
Exemple #23
0
        /// <summary>
        /// Creates a new <see cref="Texture3D{TTexel}"/> with the supplied builder parameters.
        /// </summary>
        /// <remarks>
        /// In debug mode, this method will check a large number of <see cref="Assure">assurances</see>
        /// on the builder parameters before creating the resource.
        /// </remarks>
        /// <returns>A new <see cref="Texture3D{TTexel}"/>.</returns>
        public unsafe override Texture3D <TTexel> Create()
        {
            Assure.True(Usage != ResourceUsage.Immutable || InitialData != null, "You must supply initial data to an immutable resource.");
            Assure.False(
                (Usage == ResourceUsage.Immutable || Usage == ResourceUsage.DiscardWrite) && permittedBindings == GPUBindings.None,
                "An immutable or discard-write resource with no permitted bindings is useless."
                );
            Assure.False(
                Usage.GetUsage() == 0x3 && permittedBindings != GPUBindings.None,
                "Staging resources can not be bound to the pipeline."
                );
            Assure.False((Usage == ResourceUsage.DiscardWrite || Usage == ResourceUsage.Immutable) &&
                         ((permittedBindings & GPUBindings.RenderTarget) > 0 ||
                          (permittedBindings & GPUBindings.DepthStencilTarget) > 0 ||
                          (permittedBindings & GPUBindings.WritableShaderResource) > 0),
                         "Can not bind an immutable or discard-write texture as a render target or depth stencil target, or as a GPU-writeable shader resource."
                         );

            Assure.GreaterThan(width, 0U, "Please specify a width for the texture.");
            Assure.GreaterThan(height, 0U, "Please specify a height for the texture.");
            Assure.GreaterThan(depth, 0U, "Please specify a depth for the texture.");

            Assure.False(
                mipAllocation && !MathUtils.IsPowerOfTwo(width),
                "Can not create mipmapped texture with any non-power-of-two (NPOT) dimension. " +
                "Dimensions: " + width + "x" + height + "x" + depth + "."
                );
            Assure.False(
                mipAllocation && !MathUtils.IsPowerOfTwo(height),
                "Can not create mipmapped texture with any non-power-of-two (NPOT) dimension. " +
                "Dimensions: " + width + "x" + height + "x" + depth + "."
                );
            Assure.False(
                mipAllocation && !MathUtils.IsPowerOfTwo(depth),
                "Can not create mipmapped texture with any non-power-of-two (NPOT) dimension. " +
                "Dimensions: " + width + "x" + height + "x" + depth + "."
                );
            Assure.False(
                mipAllocation && Usage == ResourceUsage.DiscardWrite,
                "Can not allocate mips on a discard-write texture."
                );
            Assure.False(
                mipGenerationTarget && !mipAllocation,
                "Can not generate mips without allocating space for them."
                );
            Assure.False(
                mipGenerationTarget &&
                ((permittedBindings & GPUBindings.RenderTarget) == 0x0 || (permittedBindings & GPUBindings.ReadableShaderResource) == 0x0),
                "To make a texture a viable mip generation target, it must be created with the RenderTarget and ReadableShaderResource GPU bindings."
                );
            Assure.False(
                mipGenerationTarget && InitialData != null,
                "Can not supply initial data to a mip generation target."
                );
            Assure.True(
                InitialData == null ||
                (InitialData.Value.Length == TextureUtils.GetSizeTexels(mipAllocation, width, height, depth)),
                "Initial data is of incorrect length (" + (InitialData != null ? InitialData.Value.Length : 0) + ") for this resource. " +
                "It should have a length of: " + TextureUtils.GetSizeTexels(mipAllocation, width, height, depth) + "."
                );
            Assure.False(dynamicDetail && Usage.GetUsage() == 0x3, "Can not create a dynamic-detail staging resource.");
            Assure.False(
                (permittedBindings & GPUBindings.DepthStencilTarget) == GPUBindings.DepthStencilTarget &&
                texelFormat != TexelFormat.DSV_FORMAT_CODE,
                "Can not create a depth-stencil target with any texel format other than " + typeof(TexelFormat.DepthStencil).Name + "."
                );

            Texture3DResourceHandle outResourceHandle;
            GCHandle?pinnedInitData   = null;
            GCHandle?pinnedDataHandle = null;
            IntPtr   initialDataPtr   = IntPtr.Zero;

            InitialResourceDataDesc[] dataArr = null;

            if (InitialData != null)
            {
                pinnedInitData = GCHandle.Alloc(InitialData.Value.ContainingArray, GCHandleType.Pinned);

                dataArr = InitialResourceDataDesc.CreateDataArr(
                    pinnedInitData.Value.AddrOfPinnedObject() + (int)(InitialData.Value.Offset * texelSizeBytes),
                    1U,
                    numMips,
                    width,
                    height,
                    depth,
                    texelSizeBytes
                    );

                pinnedDataHandle = GCHandle.Alloc(dataArr, GCHandleType.Pinned);
                initialDataPtr   = pinnedDataHandle.Value.AddrOfPinnedObject();
            }

            try {
                InteropUtils.CallNative(NativeMethods.ResourceFactory_CreateTexture3D,
                                        RenderingModule.Device,
                                        width,
                                        height,
                                        depth,
                                        (InteropBool)mipAllocation,
                                        texelFormat,
                                        Usage.GetUsage(),
                                        Usage.GetCPUUsage(),
                                        (PipelineBindings)permittedBindings,
                                        (InteropBool)mipGenerationTarget,
                                        (InteropBool)dynamicDetail,
                                        initialDataPtr,
                                        dataArr != null ? (uint)dataArr.Length : 0U,
                                        (IntPtr)(&outResourceHandle)
                                        ).ThrowOnFailure();
            }
            finally {
                if (pinnedDataHandle != null)
                {
                    pinnedDataHandle.Value.Free();
                }
                if (pinnedInitData != null)
                {
                    pinnedInitData.Value.Free();
                }
            }

            return(new Texture3D <TTexel>(
                       outResourceHandle,
                       Usage,
                       TextureUtils.GetSize(texelSizeBytes, mipAllocation, width, height, depth),
                       permittedBindings,
                       mipGenerationTarget,
                       dynamicDetail,
                       width,
                       height,
                       depth,
                       texelSizeBytes,
                       mipAllocation,
                       numMips,
                       0U
                       ));
        }
Exemple #24
0
 protected static void QueueShaderSwitch(Shader shader)
 {
     Assure.NotNull(shader);
     Assure.False(shader.IsDisposed, "Shader was disposed.");
     shader.RCQSwitchToShader(ThreadLocalRCQ);
 }
 public static RenderCommand SetInputLayout(GeometryInputLayout inputLayout)
 {
     Assure.NotNull(inputLayout);
     Assure.False(inputLayout.IsDisposed, "Input layout was disposed.");
     return(new RenderCommand(RenderCommandInstruction.SetInputLayout, (IntPtr)inputLayout.ResourceHandle));
 }
 public static RenderCommand SetBlendState(BlendState bs)
 {
     Assure.NotNull(bs);
     Assure.False(bs.IsDisposed, "Blend state was disposed.");
     return(new RenderCommand(RenderCommandInstruction.SetBlendState, (IntPtr)bs.ResourceHandle));
 }
 public static RenderCommand SetDepthStencilState(DepthStencilState ds)
 {
     Assure.NotNull(ds);
     Assure.False(ds.IsDisposed, "Depth stencil state was disposed.");
     return(new RenderCommand(RenderCommandInstruction.SetDSState, (IntPtr)ds.ResourceHandle));
 }
 public static RenderCommand SetRasterizerState(RasterizerState rs)
 {
     Assure.NotNull(rs);
     Assure.False(rs.IsDisposed, "Rasterizer state was disposed.");
     return(new RenderCommand(RenderCommandInstruction.SetRSState, (IntPtr)rs.ResourceHandle));
 }
Exemple #29
0
        public static Font Load(string fontFile, FragmentShader textFS, uint?lineHeightPixels, int?kerningPixels)
        {
            Assure.NotNull(fontFile);
            Assure.NotNull(textFS);
            Assure.False(textFS.IsDisposed);
            if (!IOUtils.IsValidFilePath(fontFile) || !File.Exists(fontFile))
            {
                throw new FileNotFoundException("File '" + fontFile + "' not found: Could not load font.");
            }

            XDocument fontDocument  = XDocument.Load(fontFile, LoadOptions.None);
            XElement  root          = fontDocument.Root;
            XElement  commonElement = root.Element("common");

            if (commonElement == null)
            {
                throw new InvalidOperationException("Could not find common element in given font file.");
            }

            string name = Path.GetFileNameWithoutExtension(fontFile).CapitalizeFirst();
            uint   texWidth;
            uint   texHeight;

            try {
                texWidth  = uint.Parse(commonElement.Attribute("scaleW").Value);
                texHeight = uint.Parse(commonElement.Attribute("scaleH").Value);
                if (lineHeightPixels == null)
                {
                    lineHeightPixels = uint.Parse(commonElement.Attribute("lineHeight").Value) / 2U;
                }
            }
            catch (Exception e) {
                throw new InvalidOperationException("Could not read scaleW, scaleH, or lineHeight value!", e);
            }

            XElement pagesElement = root.Element("pages");
            IEnumerable <XElement> pageElements = pagesElement.Elements("page");

            ITexture2D[]         pageArray          = new ITexture2D[pageElements.Count()];
            ShaderResourceView[] characterPageViews = new ShaderResourceView[pageArray.Length];

            foreach (XElement pageElement in pageElements)
            {
                int    id;
                string filename;
                try {
                    id       = int.Parse(pageElement.Attribute("id").Value);
                    filename = pageElement.Attribute("file").Value;
                }
                catch (Exception e) {
                    throw new InvalidOperationException("Could not read page ID or filename for page " + pageElement + ".", e);
                }

                string fullFilename = Path.Combine(Path.GetDirectoryName(fontFile), filename);
                if (!IOUtils.IsValidFilePath(fullFilename) || !File.Exists(fullFilename))
                {
                    throw new InvalidOperationException("Page file '" + fullFilename + "' does not exist!");
                }
                if (id < 0 || id >= pageArray.Length || pageArray[id] != null)
                {
                    throw new InvalidOperationException("Invalid or duplicate page ID '" + id + "'.");
                }

                pageArray[id] = TextureFactory.LoadTexture2D()
                                .WithFilePath(fullFilename)
                                .WithPermittedBindings(GPUBindings.ReadableShaderResource)
                                .WithUsage(ResourceUsage.Immutable)
                                .Create();

                characterPageViews[id] = pageArray[id].CreateView();
            }

            GeometryCacheBuilder <DefaultVertex> characterCacheBuilder = new GeometryCacheBuilder <DefaultVertex>();
            Dictionary <char, FontCharacter>     charMap = new Dictionary <char, FontCharacter>();
            XElement charsElement = root.Element("chars");

            foreach (XElement charElement in charsElement.Elements("char"))
            {
                char unicodeValue;
                uint x, y, width, height;
                int  pageID, yOffset;

                try {
                    unicodeValue = (char)short.Parse(charElement.Attribute("id").Value);
                    x            = uint.Parse(charElement.Attribute("x").Value);
                    y            = uint.Parse(charElement.Attribute("y").Value);
                    width        = uint.Parse(charElement.Attribute("width").Value);
                    height       = uint.Parse(charElement.Attribute("height").Value);
                    pageID       = int.Parse(charElement.Attribute("page").Value);
                    yOffset      = int.Parse(charElement.Attribute("yoffset").Value);
                }
                catch (Exception e) {
                    throw new InvalidOperationException("Could not acquire character ID, page ID, or dimensions for char " + charElement + ".", e);
                }

                Rectangle charMapBoundary = new Rectangle(x, y, width, height);

                ModelHandle modelHandle = characterCacheBuilder.AddModel(
                    "Font_" + name + "_Character_" + unicodeValue,
                    new[] {
                    new DefaultVertex(
                        new Vector3(0f, 0f, 1f),
                        Vector3.BACKWARD, new Vector2(
                            charMapBoundary.GetCornerX(Rectangle.RectangleCorner.BottomLeft) / texWidth,
                            charMapBoundary.GetCornerY(Rectangle.RectangleCorner.BottomLeft) / texHeight
                            )),
                    new DefaultVertex(
                        new Vector3(charMapBoundary.Width, 0f, 1f),
                        Vector3.BACKWARD, new Vector2(
                            charMapBoundary.GetCornerX(Rectangle.RectangleCorner.BottomRight) / texWidth,
                            charMapBoundary.GetCornerY(Rectangle.RectangleCorner.BottomRight) / texHeight
                            )),
                    new DefaultVertex(
                        new Vector3(charMapBoundary.Width, -charMapBoundary.Height, 1f),
                        Vector3.BACKWARD, new Vector2(
                            charMapBoundary.GetCornerX(Rectangle.RectangleCorner.TopRight) / texWidth,
                            charMapBoundary.GetCornerY(Rectangle.RectangleCorner.TopRight) / texHeight
                            )),
                    new DefaultVertex(
                        new Vector3(0f, -charMapBoundary.Height, 1f),
                        Vector3.BACKWARD, new Vector2(
                            charMapBoundary.GetCornerX(Rectangle.RectangleCorner.TopLeft) / texWidth,
                            charMapBoundary.GetCornerY(Rectangle.RectangleCorner.TopLeft) / texHeight
                            )),
                },
                    new[] { 0U, 1U, 3U, 1U, 2U, 3U }
                    );

                //yOffset = 0;
                //if (unicodeValue == '.') yOffset = (int) (lineHeightPixels.Value * 0.9f);

                charMap.Add(
                    unicodeValue,
                    new FontCharacter(
                        unicodeValue,
                        charMapBoundary,
                        modelHandle,
                        textFS,
                        characterPageViews[pageID],
                        yOffset
                        )
                    );
            }

            if (kerningPixels == null)
            {
                kerningPixels = (int)(charMap.Values.Max(value => value.Boundary.Width) * 0.15f);
            }

            uint maxCharHeight = (uint)charMap.Values.Max(fc => fc.Boundary.Height);

            return(new Font(
                       name,
                       lineHeightPixels.Value,
                       kerningPixels.Value,
                       characterCacheBuilder.Build(),
                       pageArray,
                       characterPageViews,
                       charMap,
                       (ConstantBufferBinding)textFS.GetBindingByIdentifier(TEXT_COLOR_SHADER_CB_NAME),
                       maxCharHeight
                       ));
        }
 public static RenderCommand SetViewport(SceneViewport vp)
 {
     Assure.NotNull(vp);
     Assure.False(vp.IsDisposed, "Viewport was disposed.");
     return(new RenderCommand(RenderCommandInstruction.SetViewport, (IntPtr)vp.ViewportHandle));
 }