public void Resize(IConstantBuffer buffer, int newElements, int newByteStride = -1, IntPtr?newData = null) { MyRenderProxy.Assert(newElements > 0); MyRenderProxy.Assert(newByteStride > 0 || newByteStride == -1); ResizeInternal(buffer as MyConstantBuffer, newElements, newByteStride, newData); }
public bool GetOrCreateModels(string filepath, out MyModels models) { filepath = MyMwmUtils.GetFullMwmFilepath(filepath); if (m_models.TryGetValue(filepath, out models)) { return(true); } // Load mwm as first lod MyMwmData firstLodMwmData = new MyMwmData(); if (!firstLodMwmData.LoadFromFile(filepath)) { MyRender11.Log.WriteLine(string.Format("Mwm '{0}' cannot be loaded from file", filepath)); return(false); } if (!IsModelSuitable(firstLodMwmData)) { return(false); } MyRenderProxy.Assert(!m_models.ContainsKey(firstLodMwmData.MwmFilepath)); models = CreateModels(firstLodMwmData); m_models.Add(firstLodMwmData.MwmFilepath, models); return(true); }
public IIndexBuffer CreateIndexBuffer(string name, int elements, IntPtr?initData = null, MyIndexBufferFormat format = MyIndexBufferFormat.UShort, ResourceUsage usage = ResourceUsage.Default) { MyRenderProxy.Assert(elements > 0); Debug.Assert(usage != ResourceUsage.Staging, "Conspicuous ResourceUsage setup: should an index buffer be a staging resource?"); int stride; switch (format) { case MyIndexBufferFormat.UShort: stride = 2; break; case MyIndexBufferFormat.UInt: stride = 4; break; default: throw new NotImplementedException("Unsupported index buffer format."); } BufferDescription description = new BufferDescription(elements * stride, usage, BindFlags.IndexBuffer, usage == ResourceUsage.Dynamic ? CpuAccessFlags.Write : CpuAccessFlags.None, ResourceOptionFlags.None, stride); return(CreateInternal <MyIndexBuffer>(name, ref description, initData, b => b.Format = format)); }
// the functionality is not clear to me, the code is legacy from the old pipeline Byte4[] CreateAlteredTangents(Byte4[] normals, Byte4[] tangents, Byte4[] bitangents) { int verticesNum = tangents.Length; var alteredTangents = new Byte4[verticesNum]; if (tangents.Length > 0 && bitangents.Length > 0) { MyRenderProxy.Assert(normals.Length == tangents.Length && normals.Length == bitangents.Length); // calculate tangents used by run-time for (int i = 0; i < verticesNum; i++) { var N = VF_Packer.UnpackNormal(normals[i].PackedValue); var T = VF_Packer.UnpackNormal(tangents[i].PackedValue); var B = VF_Packer.UnpackNormal(bitangents[i].PackedValue); var tanW = new Vector4(T.X, T.Y, T.Z, 0); tanW.W = T.Cross(N).Dot(B) < 0 ? -1 : 1; alteredTangents[i] = VF_Packer.PackTangentSignB4(ref tanW); } } return(alteredTangents); }
public static int GetSingleDepthPassIdx(int id) { var i = id - MaxGBufferPassesCount - MaxCascadeDepthPassesCount; MyRenderProxy.Assert(i < MaxSingleDepthPassesCount); return(i); }
internal static void UpdateData(MyGPUEmitter[] def) { for (int i = 0; i < def.Length; i++) { MyLiveData emitter; if (m_emitters.TryGetValue(def[i].GID, out emitter)) { var texId = Resources.MyTextures.GetTexture(def[i].AtlasTexture, Resources.MyTextureEnum.GUI, true); if (emitter.TextureId != texId) { RemoveTexture(emitter.TextureId); AddTexture(texId); } emitter.TextureId = texId; MyRenderProxy.Assert(emitter.TextureId != Resources.TexId.NULL); emitter.GPUEmitter = def[i]; emitter.GPUEmitter.Data.TextureIndex1 = GenerateTextureIndex(emitter); emitter.GPUEmitter.Data.TextureIndex2 = (uint)def[i].AtlasFrameModulo; emitter.GPUEmitter.Data.RotationMatrix = Matrix.Transpose(def[i].Data.RotationMatrix); } else { MyRenderProxy.Assert(false, "invalid emitter id: " + def[i].GID); } } }
private static IResource GetResource(string filepath, MyFileTextureEnum type, MyFileArrayTexture referenceArray, int referenceSlice, Vector2I textureSize, out Texture2DDescription description, out int sourceSlice) { if (referenceArray != null && referenceSlice < referenceArray.Size3.Z && referenceArray.Size == textureSize && filepath == referenceArray.SubresourceFilenames[referenceSlice]) { var tex2d = referenceArray.Resource as Texture2D; description = tex2d.Description; sourceSlice = referenceSlice; return(referenceArray); } else { var texture = MyManagers.FileTextures.GetTexture(filepath, type, true, temporary: true); var tex2d = texture.Resource as Texture2D; if (tex2d == null) { var tex2D = texture.Resource as Texture2D; MyRenderProxy.Assert(tex2D != null, "MyFileArrayTexture supports only 2D textures. Inconsistent texture: " + filepath); description = new Texture2DDescription(); sourceSlice = -1; return(null); } description = tex2d.Description; sourceSlice = 0; return(texture); } }
internal static void UpdateData(MyGPUEmitter[] def) { for (int i = 0; i < def.Length; i++) { MyLiveData emitter; if (m_emitters.TryGetValue(def[i].GID, out emitter)) { MarkTextureUnused(emitter.GPUEmitter.AtlasTexture); AddTexture(def[i].AtlasTexture); emitter.GPUEmitter = def[i]; emitter.GPUEmitter.Data.TextureIndex1 = GenerateTextureIndex(emitter); emitter.GPUEmitter.Data.TextureIndex2 = (uint)def[i].AtlasFrameModulo; emitter.GPUEmitter.Data.RotationMatrix = Matrix.Transpose(def[i].Data.RotationMatrix); if (emitter.JustAdded) { emitter.LastWorldPosition = emitter.GPUEmitter.WorldPosition; } emitter.JustAdded = false; } else { MyRenderProxy.Assert(false, "invalid emitter id: " + def[i].GID); } } }
public IBorrowedRtvTexture BorrowRtv(string debugName, int width, int height, Format format, int samplesCount = 1, int samplesQuality = 0) { MyRenderProxy.Assert(width > 0); MyRenderProxy.Assert(height > 0); MyBorrowedTextureKey key = new MyBorrowedTextureKey { Width = width, Height = height, Format = format, SamplesCount = samplesCount, SamplesQuality = samplesQuality, }; if (!m_dictionaryRtvTextures.ContainsKey(key)) { AddNewRtvsList(key); } List <MyBorrowedRtvTexture> list = m_dictionaryRtvTextures[key]; foreach (var texIt in list) { if (!texIt.IsBorrowed) { texIt.SetBorrowed(debugName, m_currentFrameNum); return(texIt); } } MyBorrowedRtvTexture createdTex = CreateRtv(debugName, key); createdTex.SetBorrowed(debugName, m_currentFrameNum); return(createdTex); }
internal void InitAndRegister(MyInstanceComponent instance, MyModels models, bool isVisible, MyVisibilityExtFlags visibilityExt, MyCompatibilityDataForTheOldPipeline compatibilityData) { MyRenderProxy.Assert(!m_instances.Contains(instance)); instance.InitInternal(models, isVisible, visibilityExt, compatibilityData); m_instances.Add(instance); }
static MyFileTextureEnum GetTextureType(MyChannel channel) { MyFileTextureEnum type = MyFileTextureEnum.UNSPECIFIED; switch (channel) { case MyChannel.ColorMetal: type = MyFileTextureEnum.COLOR_METAL; break; case MyChannel.NormalGloss: type = MyFileTextureEnum.NORMALMAP_GLOSS; break; case MyChannel.Extension: type = MyFileTextureEnum.EXTENSIONS; break; case MyChannel.Alphamask: type = MyFileTextureEnum.ALPHAMASK; break; default: MyRenderProxy.Assert(false, "Channel is not recognised"); break; } return(type); }
internal static void UpdateEmitters(MyGPUEmitter[] def) { m_overloaded = false; for (int i = 0; i < def.Length; i++) { var id = m_idIndex.Get(def[i].GID, GPUEmitterId.NULL); MyRenderProxy.Assert(id != GPUEmitterId.NULL); if (id != GPUEmitterId.NULL) { m_totalParticles -= m_emitters.Data[id.Index].GPUEmitter.MaxParticles(); var texId = Resources.MyTextures.GetTexture(def[i].AtlasTexture, Resources.MyTextureEnum.GUI, true); if (m_emitters.Data[id.Index].TextureId != texId) { RemoveTexture(m_emitters.Data[id.Index].TextureId); AddTexture(texId); } m_emitters.Data[id.Index].TextureId = texId; MyRenderProxy.Assert(m_emitters.Data[id.Index].TextureId != Resources.TexId.NULL); def[i].Data.TextureIndex1 = GenerateTextureIndex(def[i]); def[i].Data.TextureIndex2 = (uint)def[i].AtlasFrameModulo; m_emitters.Data[id.Index].GPUEmitter = def[i]; if ((m_totalParticles + def[i].MaxParticles()) > MAX_PARTICLES) { m_emitters.Data[id.Index].GPUEmitter.ParticlesPerSecond = 0; m_overloaded = true; MyRenderProxy.Assert(false, "GPU Particle system overloaded."); } m_totalParticles += m_emitters.Data[id.Index].GPUEmitter.MaxParticles(); } } }
unsafe IConstantBuffer GetShadowConstants(ICascadeShadowMap csm, ref MyShadowsSettings settings) { const int MAX_SLICES_COUNT = 8; MyRenderProxy.Assert(csm.SlicesCount <= MAX_SLICES_COUNT, "It is not supported more than 8 slices per cascade shadow map"); int size = sizeof(Matrix) * MAX_SLICES_COUNT + sizeof(Vector4) * MAX_SLICES_COUNT; IConstantBuffer cb = MyCommon.GetObjectCB(size); var mapping = MyMapping.MapDiscard(cb); for (int i = 0; i < csm.SlicesCount; i++) { // Set matrices: Matrix matrix = csm.GetSlice(i).MatrixWorldAt0ToShadowSpace; matrix = matrix * Matrix.CreateTranslation(1, -1, 0); Vector2 scalingFactor = new Vector2(0.5f, -0.5f); matrix = matrix * Matrix.CreateScale(scalingFactor.X, scalingFactor.Y, 1); matrix = Matrix.Transpose(matrix); mapping.WriteAndPosition(ref matrix); // Set normal offsets: mapping.WriteAndPosition(ref settings.Cascades[i].ShadowNormalOffset); float zero = 0; for (int j = 1; j < 4; j++) { mapping.WriteAndPosition(ref zero); } } mapping.Unmap(); return(cb); }
public bool CheckConsistency(string[] inputFiles) { MyRenderProxy.Assert(inputFiles.Length != 0); MyFileTextureManager texManager = MyManagers.FileTextures; ISrvBindable firstSrvBindable = texManager.GetTexture(inputFiles[0], MyFileTextureEnum.GPUPARTICLES, true); Texture2D firstTex2D = firstSrvBindable.Resource as Texture2D; if (firstTex2D == null) { return(false); } for (int i = 1; i < inputFiles.Length; i++) { ISrvBindable srvBindable = texManager.GetTexture(inputFiles[i], MyFileTextureEnum.GPUPARTICLES, true); Texture2D tex2D = srvBindable.Resource as Texture2D; if (tex2D == null) { return(false); } bool consistent = MyResourceUtils.CheckTexturesConsistency(firstTex2D.Description, tex2D.Description); if (!consistent) { return(false); } } return(true); }
internal void Initialize(DeviceContext context = null) { MyRenderProxy.Assert(m_deviceContext == null, "Initialize is called to already initialized object. Whether initialization has been performed or not, check by the method 'IsInitialized()'"); if (context == null) { context = new DeviceContext(MyRender11.Device); m_isDeferred = true; } else { m_isDeferred = false; } m_deviceContext = context; m_vertexShaderStage.Init(m_deviceContext, m_deviceContext.VertexShader, m_statistics); m_geometryShaderStage.Init(m_deviceContext, m_deviceContext.GeometryShader, m_statistics); m_pixelShaderStage.Init(m_deviceContext, m_deviceContext.PixelShader, m_statistics); m_computeShaderStage.Init(m_deviceContext, m_deviceContext.ComputeShader, m_statistics); m_state.Init(m_deviceContext, m_statistics); if (m_annotations == null) { m_annotations = m_deviceContext.QueryInterface <SharpDX.Direct3D11.UserDefinedAnnotation>(); } m_statistics.Clear(); }
public IDepthStencil CreateDepthStencil(string debugName, int width, int height, Format resourceFormat = Format.R32G8X24_Typeless, Format dsvFormat = Format.D32_Float_S8X24_UInt, Format srvDepthFormat = Format.R32_Float_X8X24_Typeless, Format srvStencilFormat = Format.X32_Typeless_G8X24_UInt, int samplesCount = 1, int samplesQuality = 0) { MyRenderProxy.Assert(width > 0); MyRenderProxy.Assert(height > 0); MyDepthStencil tex = m_objectsPool.Allocate(); tex.Init(debugName, width, height, resourceFormat, dsvFormat, srvDepthFormat, srvStencilFormat, samplesCount, samplesQuality); if (m_isDeviceInit) { try { tex.OnDeviceInit(); } catch (System.Exception ex) { IDepthStencil t = tex; DisposeTex(ref t); throw; } } return(tex); }
internal void SetVertexBuffers(int startSlot, Buffer[] vbs, int[] strides) { MyRenderProxy.Assert(startSlot + vbs.Length < m_vertexBuffers.Length); bool same = true; for (int i = startSlot; i < startSlot + vbs.Length; i++) { if (vbs[i] != m_vertexBuffers[i] || strides[i] != m_vertexBuffersStrides[i]) { same = false; } } if (same) { return; } for (int i = 0; i < vbs.Length; i++) { m_vertexBuffers[i + startSlot] = vbs[i]; m_vertexBuffersStrides[i + startSlot] = strides[i]; } m_deviceContext.InputAssembler.SetVertexBuffers(startSlot, vbs, strides, null); m_statistics.SetVertexBuffers++; }
void InternalSetRtvs(DepthStencilView dsv, params IRtvBindable[] rtvs) { if (m_tmpRtvs == null) { m_tmpRtvs = new RenderTargetView[8]; } // Init RenderTargetView-s MyRenderProxy.Assert(rtvs.Length <= m_tmpRtvs.Length); for (int i = 0; i < rtvs.Length; i++) { IRtvBindable rtvBindable = rtvs[i]; RenderTargetView dxObject = null; if (rtvBindable != null) { dxObject = rtvBindable.Rtv; } m_tmpRtvs[i] = dxObject; } for (int i = rtvs.Length; i < m_tmpRtvs.Length; i++) { m_tmpRtvs[i] = null; } m_state.SetTargets(dsv, m_tmpRtvs, rtvs.Length); CheckErrors(); }
internal static void Remove(uint GID, bool instant = true, bool check = true) { MyLiveData emitter; if (m_emitters.TryGetValue(GID, out emitter)) { if (emitter.BufferIndex == -1) { Remove(emitter); } else if (instant) { emitter.GPUEmitter.Data.Flags |= GPUEmitterFlags.Dead; } else { emitter.GPUEmitter.ParticlesPerSecond = 0; emitter.DieAt = MyCommon.TimerMs + emitter.GPUEmitter.Data.ParticleLifeSpan * 1000; } } else { MyRenderProxy.Assert(check, "Invalid emitter id: " + GID); } }
public IBorrowedDepthStencilTexture BorrowDepthStencil(string debugName, int width, int height, int samplesCount = 1, int samplesQuality = 0) { MyRenderProxy.Assert(width > 0); MyRenderProxy.Assert(height > 0); MyBorrowedTextureKey key = new MyBorrowedTextureKey { Width = width, Height = height, Format = Format.Unknown, SamplesCount = samplesCount, SamplesQuality = samplesQuality, }; if (!m_dictionaryDepthStencilTextures.ContainsKey(key)) { m_dictionaryDepthStencilTextures.Add(key, new List <MyBorrowedDepthStencilTexture>()); } foreach (var texIt in m_dictionaryDepthStencilTextures[key]) { if (!texIt.IsBorrowed) { texIt.SetBorrowed(debugName, m_currentFrameNum); return(texIt); } } MyBorrowedDepthStencilTexture createdTex = CreateDepthStencil(debugName, key); createdTex.SetBorrowed(debugName, m_currentFrameNum); return(createdTex); }
// the method is static, because of removal all of the references on the member variables static unsafe IVertexBuffer CreateSimpleVB1(MyMwmData mwmData) { MyRenderProxy.Assert(mwmData.IsValid2ndStream); string name = "VB1-" + mwmData.MwmFilepath; //Byte4 texIndices = new Byte4(0, 0, 0, 0); var vertices = new MyVertexFormatTexcoordNormalTangent[mwmData.VerticesCount]; fixed(MyVertexFormatTexcoordNormalTangent *destinationPointer = vertices) { for (int vertexIndex = 0; vertexIndex < mwmData.VerticesCount; ++vertexIndex) { destinationPointer[vertexIndex].Normal = mwmData.Normals[vertexIndex]; destinationPointer[vertexIndex].Tangent = mwmData.Tangents[vertexIndex]; destinationPointer[vertexIndex].Texcoord = mwmData.Texcoords[vertexIndex]; //destinationPointer[vertexIndex].TexIndices = texIndices; } } fixed(void *ptr = vertices) { return(MyManagers.Buffers.CreateVertexBuffer(name, vertices.Length, MyVertexFormatTexcoordNormalTangent.STRIDE, new IntPtr(ptr), ResourceUsage.Immutable)); } }
public void SetBorrowed(string name, int currentFrameNum) { MyRenderProxy.Assert(!IsBorrowed, "The texture has been borrowed."); LastUsedDebugName = name; LastUsedInFrameNum = currentFrameNum; m_numRefs = 1; }
// complex implemtation because of the IPrioritizedWork, the simple way is to call Draw directly... public void InitWork(List <MyInstanceComponent> visibleInstances) { MyRenderProxy.Assert(m_visibleInstancesForDoWork == null, "It is needed to call DoWork() after InitWork()"); m_visibleInstancesForDoWork = visibleInstances; m_RC = MyManagers.DeferredRCs.AcquireRC(); Stats.Clear(); }
public void DisposeTex(IGeneratedTexture tex) { if (tex == null) { return; } if (tex is MyUserGeneratedTexture) { MyUserGeneratedTexture texture = (MyUserGeneratedTexture)tex; texture.Dispose(); m_objectsPoolGenerated.Deallocate(texture); tex = null; } else if (tex is MyGeneratedTextureFromPattern) { MyGeneratedTextureFromPattern texture = (MyGeneratedTextureFromPattern)tex; texture.Dispose(); m_objectsPoolGeneratedFromPattern.Deallocate(texture); tex = null; } else { MyRenderProxy.Assert(false, "It is disposed texture that does not belong to this manager"); } }
/// <remarks>On big loops, or whenever recommendable, cache the returned reference</remarks> public ITexture GetTexture(string name, MyFileTextureEnum type, bool waitTillLoaded = false, bool skipQualityReduction = false) { if (name == null || name.Length <= 0) { return(ReturnDefaultTexture(type)); } Uri uri; if (!MyResourceUtils.NormalizeFileTextureName(ref name, out uri)) { IGeneratedTexture texture; if (m_generatedTextures.TryGetValue(name, out texture)) { return(texture); } else { MyRenderProxy.Assert(false, "Can't find generated texture with name \"" + name + "\""); return(ReturnDefaultTexture(type)); } } MyFileTexture texOut; if (!m_textures.TryGetValue(name, out texOut)) { if (uri.Scheme != FILE_SCHEME) { Debug.Assert(false, "Cannot initialize a non file texture"); return(ReturnDefaultTexture(type)); } m_texturesPool.AllocateOrCreate(out texOut); texOut.Init(name, uri.LocalPath, type, waitTillLoaded, skipQualityReduction); m_textures.Add(name, texOut); } switch (texOut.TextureState) { case FileTextureState.Unloaded: case FileTextureState.Requested: if (waitTillLoaded) { LoadInternal(name); } else { texOut.TextureState = FileTextureState.Requested; m_requestedTextures.Add(name); } break; case FileTextureState.Loaded: break; } return(texOut); }
public void OnDeviceInit() { ISrvBindable firstTex = MyManagers.FileTextures.GetTexture(m_listSubresourceFilenames[0], m_type, true); var srcDesc = firstTex.Srv.Description; Vector2I Size = firstTex.Size; Texture2DDescription desc = new Texture2DDescription(); desc.ArraySize = m_listSubresourceFilenames.Count; desc.BindFlags = BindFlags.ShaderResource; desc.CpuAccessFlags = CpuAccessFlags.None; desc.Format = srcDesc.Format; desc.Height = (int)Size.Y; desc.Width = (int)Size.X; desc.MipLevels = srcDesc.Texture2D.MipLevels; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; desc.Usage = ResourceUsage.Default; m_resource = new Texture2D(MyRender11.Device, desc); m_resource.DebugName = m_resourceName; TextureFormat = srcDesc.Format; // foreach mip var mipmaps = srcDesc.Texture2D.MipLevels; int i = 0; foreach (var path in m_listSubresourceFilenames) { ISrvBindable tex = MyManagers.FileTextures.GetTexture(path, m_type, true); var tex2D = tex.Resource as Texture2D; MyRenderProxy.Assert(tex2D != null, "MyTextureArray supports only 2D textures. Inconsistent texture: " + tex.Name); bool consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description); if (!consistent) { string errorMsg = "All MyTextureArray has to have the same pixel format, width / height and # of mipmaps. Inconsistent textures: " + tex.Name + " / " + firstTex.Name; MyRenderProxy.Error(errorMsg); MyRender11.Log.WriteLine(errorMsg); } for (int m = 0; m < mipmaps; m++) { MyRender11.RC.CopySubresourceRegion(tex2D, Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource, Resource.CalculateSubResourceIndex(m, i, mipmaps)); int sizeX = Resource.CalculateMipSize(m, Size.X); int sizeY = Resource.CalculateMipSize(m, Size.Y); ByteSize += FormatHelper.ComputeScanlineCount(TextureFormat, sizeX) * 4 * FormatHelper.ComputeScanlineCount(TextureFormat, sizeY) * 4 * FormatHelper.SizeOfInBytes(TextureFormat); } i++; } m_srv = new ShaderResourceView(MyRender11.Device, Resource); }
public void DisposeCsm(ICascadeShadowMap csm) { MyCascadeShadowMap myCsm = (MyCascadeShadowMap)csm; MyRenderProxy.Assert(!m_objectsPoolCsm.Active.Contains(myCsm), "Shadowmap is not active, maybe it is disposed already."); myCsm.Destroy(); m_objectsPoolCsm.Deallocate(myCsm); }
public MyLod GetLod(int lod) { MyRenderProxy.Assert(m_lods.Count >= 1); MyRenderProxy.Assert(lod < m_lodStrategyInfo.GetLodsCount()); MyRenderProxy.Assert(lod < m_lods.Count); MyRenderProxy.Assert(lod >= 0); return(m_lods[lod]); }
public void DisposeSingleShadowmap(ISingleShadowmap shadowmap) { MySingleShadowmap myShadowmap = (MySingleShadowmap)shadowmap; MyRenderProxy.Assert(!m_objectsPoolSingleShadowmap.Active.Contains(myShadowmap), "Shadowmap is not active, maybe it is disposed already."); myShadowmap.Destroy(); m_objectsPoolSingleShadowmap.Deallocate(myShadowmap); }
public MyRenderContext AcquireRC() { MyRenderProxy.Assert(m_isDeviceInit); var rc = m_pool.Get(); rc.ClearState(); return(rc); }