internal void DrawSpriteGlyph(Texture2D texture, Vector4 dest, Vector4 source, Color color) { if (!m_DrawString_InProgress) Logging.Fatal("BeginDrawString() must be called before DrawSpriteGlyph()"); Vector4 uv = new Vector4( (float)source.X / texture.Width, (float)source.Y / texture.Height, (float)(source.X + source.Z) / texture.Width, (float)(source.Y + source.W) / texture.Height); VertexPositionTextureHueExtra[] v = new VertexPositionTextureHueExtra[4] { new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y, m_DrawString_Depth), new Vector2(uv.X, uv.Y), color, Vector4.Zero), // top left new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y, m_DrawString_Depth), new Vector2(uv.Z, uv.Y), color, Vector4.Zero), // top right new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.X, uv.W), color, Vector4.Zero), // bottom left new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.Z, uv.W), color, Vector4.Zero) // bottom right }; /*if (shadow != null) { Color shadow2 = new Color( shadow.Value.R, shadow.Value.G, shadow.Value.B, 128); for (int i = 0; i < 4; i++) { VertexPositionTextureHueExtra v0 = v[i]; v0.Hue = shadow.Value; v0.Position.Y += 1f; m_DrawString_VertexList.Add(v0); } }*/ for (int i = 0; i < 4; i++) m_DrawString_VertexList.Add(v[i]); }
public void ApplyDamage(Vector4 mg) { if (mg.w>maxhp) { Global.score+=points; Instantiate(explosion,transform.position,transform.rotation); Destroy(gameObject); } else { hp-=mg.w; if (hp<=0) { Instantiate(Resources.Load<GameObject>("bigdust"),transform.position,Quaternion.identity); RaycastHit rh; var layerMask=1<<11; //waterlayer if (Physics.Raycast(transform.position,Vector3.down,out rh,200,layerMask)) { Instantiate(oil_spot,rh.point,Quaternion.Euler(0,Random.value*360,0)); } Global.score+=points; Destroy(gameObject); } else { if (hp/maxhp<0.25f&&!broken) { broken=true; GameObject x=Instantiate(Resources.Load<GameObject>("fire1"),transform.position,Quaternion.identity) as GameObject; x.transform.parent=transform; x=Instantiate(Resources.Load<GameObject>("smoke"),transform.position,Quaternion.identity) as GameObject; x.transform.parent=transform; foreach (GameObject g in buildings) { Destroy(g); } } } } }
public void In( [FriendlyName("A", "The first variable or variable list.")] Vector4[] A, [FriendlyName("B", "The second variable or variable list.")] Vector4[] B, [FriendlyName("Result", "The Vector4 result of the operation.")] out Vector4 Result ) { Vector4 aTotals = new Vector4(0, 0, 0, 0); Vector4 bTotals = new Vector4(0, 0, 0, 0); foreach (Vector4 currentA in A) { aTotals += currentA; } foreach (Vector4 currentB in B) { bTotals += currentB; } Result = aTotals + bTotals; }
public void ApplyDamage(Vector4 mg) { if (mg.w>maxhp) { Global.menu_script.AddFireplace(transform.position); Global.score+=points; Destroy(gameObject); } else { hp-=mg.w; if (hp<=0) { if (use_dust) { Vector3 p=null_point; while (tall>0) { p+=transform.TransformDirection(Vector3.up*10); Global.BigDustRequest(p); tall-=10; } } Destroy(gameObject); } } if (hp<cd) { GameObject x=Instantiate(Global.r_fire,new Vector3(mg.x,mg.y,mg.z),Quaternion.LookRotation(new Vector3(mg.x,mg.y,mg.z)-transform.position)) as GameObject; x.transform.parent=transform; if (cd>0) cd-=fd; } }
public Effect(XElement element) { if (element.Attribute("id") != null) Id = element.Attribute("id").Value; if (element.Attribute("name") != null) Name = element.Attribute("name").Value; var commonElement = element.Element(XName.Get("profile_COMMON", COLLADAConverter.Namespace)); if (commonElement != null) { var techniqueElement = commonElement.Element(XName.Get("technique", COLLADAConverter.Namespace)); if (techniqueElement != null) { var phongElement = techniqueElement.Element(XName.Get("phong", COLLADAConverter.Namespace)); if (phongElement != null) { Emission = XmlReaderHelper.ReadColor(phongElement.Element(XName.Get("emission", COLLADAConverter.Namespace)).Element(XName.Get("color", COLLADAConverter.Namespace))); Ambient = XmlReaderHelper.ReadColor(phongElement.Element(XName.Get("ambient", COLLADAConverter.Namespace)).Element(XName.Get("color", COLLADAConverter.Namespace))); Specular = XmlReaderHelper.ReadColor(phongElement.Element(XName.Get("specular", COLLADAConverter.Namespace)).Element(XName.Get("color", COLLADAConverter.Namespace))); Shininess = XmlReaderHelper.ReadFloat(phongElement.Element(XName.Get("shininess", COLLADAConverter.Namespace)).Element(XName.Get("float", COLLADAConverter.Namespace))); Reflectivity = XmlReaderHelper.ReadFloat(phongElement.Element(XName.Get("reflectivity", COLLADAConverter.Namespace)).Element(XName.Get("float", COLLADAConverter.Namespace))); Transparent = XmlReaderHelper.ReadColor(phongElement.Element(XName.Get("transparent", COLLADAConverter.Namespace)).Element(XName.Get("color", COLLADAConverter.Namespace))); Transparency = XmlReaderHelper.ReadFloat(phongElement.Element(XName.Get("transparency", COLLADAConverter.Namespace)).Element(XName.Get("float", COLLADAConverter.Namespace))); var diffuseElement = phongElement.Element(XName.Get("diffuse", COLLADAConverter.Namespace)); var diffuseColorElement = diffuseElement.Element(XName.Get("color", COLLADAConverter.Namespace)); if (diffuseColorElement != null) Diffuse = XmlReaderHelper.ReadColor(diffuseColorElement); } } } }
/// 行列との掛け算 public static Vector4 Mult( ref Vector4 pos, Matrix4 mtx ) { calPos4.X = (mtx.M11 * pos.X) + (mtx.M21 * pos.Y) + ( mtx.M31 * pos.Z ) + ( mtx.M41 * pos.W ); calPos4.Y = (mtx.M12 * pos.X) + (mtx.M22 * pos.Y) + ( mtx.M32 * pos.Z ) + ( mtx.M42 * pos.W ); calPos4.Z = (mtx.M13 * pos.X) + (mtx.M23 * pos.Y) + ( mtx.M33 * pos.Z ) + ( mtx.M43 * pos.W ); return calPos4; }
public override IEnumerator Run() { m_max = QueryDisplacements.MaxRange(m_displacements, m_choppyness, m_gridScale, this); FinishedRunning(); return null; }
public VertexVoxel(Vector3 pos, Vector2 uv, Vector4 uvr, Color c) { Position = pos; UV = uv; UVRect = uvr; Tint = c; }
void Raymarch(int width, int height, Vector4 lightPos) { SetFrustumRays(m_RaymarchMaterial); int shadowmapWidth = m_Shadowmap.width; int shadowmapHeight = m_Shadowmap.height; Graphics.SetRenderTarget(m_RaymarchedLightEpi.colorBuffer, m_RaymarchedLightEpi.depthBuffer); GL.Clear(false, true, new Color(0, 0, 0, 1)); m_RaymarchMaterial.SetTexture("_Coord", m_CoordEpi); m_RaymarchMaterial.SetTexture("_InterpolationEpi", m_InterpolationEpi); m_RaymarchMaterial.SetTexture("_Shadowmap", m_Shadowmap); float brightness = m_Colored ? m_BrightnessColored/m_ColorBalance : m_Brightness; brightness *= m_Light.intensity; m_RaymarchMaterial.SetFloat("_Brightness", brightness); m_RaymarchMaterial.SetFloat("_Extinction", -m_Extinction); m_RaymarchMaterial.SetVector("_ShadowmapDim", new Vector4(shadowmapWidth, shadowmapHeight, 1.0f / shadowmapWidth, 1.0f / shadowmapHeight)); m_RaymarchMaterial.SetVector("_ScreenTexDim", new Vector4(width, height, 1.0f / width, 1.0f / height)); m_RaymarchMaterial.SetVector("_LightColor", m_Light.color.linear); m_RaymarchMaterial.SetFloat("_MinDistFromCamera", m_MinDistFromCamera); SetKeyword(m_Colored, "COLORED_ON", "COLORED_OFF"); m_RaymarchMaterial.SetTexture("_ColorFilter", m_ColorFilter); SetKeyword(m_AttenuationCurveOn, "ATTENUATION_CURVE_ON", "ATTENUATION_CURVE_OFF"); m_RaymarchMaterial.SetTexture("_AttenuationCurveTex", m_AttenuationCurveTex); Texture cookie = m_Light.cookie; SetKeyword(cookie != null, "COOKIE_TEX_ON", "COOKIE_TEX_OFF"); if (cookie != null) m_RaymarchMaterial.SetTexture("_Cookie", cookie); m_RaymarchMaterial.SetPass(0); RenderQuadSections(lightPos); }
public void Vector4_ConstructFromVector3Test() { Vector3 v3 = new Vector3(1.0f, 2.0f, 3.0f); Vector4 v4 = new Vector4(v3, 0.8f); Vector4 expected = new Vector4(v3.x, v3.y, v3.z, 0.8f); Assert.AreEqual(expected, v4); }
public static Vector4 smokeyCalc(Vector4 a, Vector4 b, double t) { return new Vector4(smokeyCalc(a.X, b.X, t), smokeyCalc(a.Y, b.Y, t), smokeyCalc(a.Z, b.Z, t), smokeyCalc(a.W, b.W, t)); }
public VertexPositionNormal4Texture(Vector3 position, Vector3 normal, Vector4 textureWeight, Vector4 textureType) { Position = position; Normal = normal; TextureWeight = textureWeight; TextureType = textureType; }
void Update() { if (Input.GetKey(KeyCode.L)) { if (!L_downflag) { L_downflag=true; if (dlight.shadows==LightShadows.None) { dlight.shadows=LightShadows.Soft; } else { dlight.shadows=LightShadows.None; } } } else { L_downflag=false; } Material mat=grass.renderer.material; Collider col=grass.collider; Ray ray = new Ray(rigidbody.position+Vector3.up, -Vector3.up); RaycastHit hit=new RaycastHit(); if (col.Raycast(ray, out hit, 100f)) { float dmp=Mathf.Clamp(1-(rigidbody.position.y-0.3042075f)/0.35f,0,1); Vector4 pos=new Vector4(hit.textureCoord.x, hit.textureCoord.y, dmp*dmp, 0); mat.SetVector("_ballpos", pos); rigidbody.drag=dmp*1.0f; float v=rigidbody.velocity.magnitude*5.0f; dmp/=(v<1) ? 1 : v; rigidbody.angularDrag=dmp*1.0f; } }
public BasicVec4(Vector4 v) { x = v.X; y = v.Y; z = v.Z; w = v.W; }
void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) { Graphics.Blit (source, destination); return; } Vector4 UV_Transform = new Vector4(1, 0, 0, 1); #if UNITY_WP8 // WP8 has no OS support for rotating screen with device orientation, // so we do those transformations ourselves. if (Screen.orientation == ScreenOrientation.LandscapeLeft) { UV_Transform = new Vector4(0, -1, 1, 0); } if (Screen.orientation == ScreenOrientation.LandscapeRight) { UV_Transform = new Vector4(0, 1, -1, 0); } if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) { UV_Transform = new Vector4(-1, 0, 0, -1); } #endif overlayMaterial.SetVector("_UV_Transform", UV_Transform); overlayMaterial.SetFloat ("_Intensity", intensity); overlayMaterial.SetTexture ("_Overlay", texture); Graphics.Blit (source, destination, overlayMaterial, (int) blendMode); }
/// <summary> /// Initializes a new instance of the <see cref="Quaternion"/> class. /// </summary> /// <param name="sourcePosition">The source position.</param> /// <param name="destinationPosition">The destination position.</param> public Quaternion(Vector3 sourcePosition, Vector3 destinationPosition) { var r = sourcePosition.Cross(destinationPosition); var s = Functions.Sqrt(2 * (1 + sourcePosition.Dot(destinationPosition))); mValues = new Vector4(r / s, s / 2); }
public void In( [FriendlyName("A", "The Vector4 to subtract from. If more than one Vector4 variable is connected to A, they will be subtracted from (0, 0, 0, 0) before B is subtracted from them.")] Vector4[] A, [FriendlyName("B", "The Vector4 to subtract from A. If more than one Vector4 variable is connected to B, they will be subtracted from (0, 0, 0, 0) before being subtracted from A.")] Vector4[] B, [FriendlyName("Result", "The Vector4 result of the subtraction operation.")] out Vector4 Result ) { Vector4 aTotals = new Vector4(0, 0, 0, 0); Vector4 bTotals = new Vector4(0, 0, 0, 0); foreach (Vector4 currentA in A) { aTotals = aTotals - currentA; } foreach (Vector4 currentB in B) { bTotals = bTotals - currentB; } Result = aTotals - bTotals; }
public override void BatchedUnitVectorGetSupportingVertexWithoutMargin(IList<Vector3> vectors, IList<Vector4> supportVerticesOut, int numVectors) { int i; Vector3 vtx = Vector3.Zero; float newDot = 0f; for (i = 0; i < numVectors; i++) { Vector4 temp = supportVerticesOut[i]; temp.W = -MathUtil.BT_LARGE_FLOAT; supportVerticesOut[i] = temp; } for (int j = 0; j < numVectors; j++) { Vector3 vec = vectors[j]; for (i = 0; i < GetNumVertices(); i++) { GetVertex(i, ref vtx); newDot = Vector3.Dot(vec, vtx); if (newDot > supportVerticesOut[j].W) { supportVerticesOut[j] = new Vector4(vtx, newDot); } } } }
public override void Start() { isStarted = true; if (duration == 0) { sprite.SetOverlay(this.toColor); if (!isInfinite) this.Stop(); return; } this.originalColor = sprite.GetOverlay(); if (isFromNull) this.fromColor = this.originalColor; // velocity = UtilityHelper.CalculateVelocity(this.fromColor, this.toColor, duration); Sign = UtilityHelper.CalculateSign(this.fromColor, this.toColor); currentColor = this.fromColor; if (isAnimatedFromOrigin) { currentColor = this.originalColor; Sign = UtilityHelper.CalculateSign(currentColor, this.fromColor); } else { sprite.SetOverlay(this.currentColor); } CurrentTime = TimeSpan.Zero; Duration = TimeSpan.FromSeconds(duration); totalDistance = UtilityHelper.VectorAbs(Vector4.Subtract(toColor, fromColor)); if (graphFunction == null) graphFunction = new ConstantGraphFunction(duration); }
public MyGuiControlCheckbox(IMyGuiControlsParent parent, Vector2 position, Vector2 size, MyTexture2D texture, MyTexture2D checkedTexture, StringBuilder toolTip, bool checkedVal, Vector4 color, bool highlightWhenChecked, MyGuiControlLabel label, Vector2? innerSize = null) : base(parent, position, size, color, toolTip, texture, null, null, true) { m_canHandleKeyboardActiveControl = true; m_checked = checkedVal; m_highlightWhenChecked = false; // highlightWhenChecked; this feature is depracted m_checkedTexture = checkedTexture; m_label = label; if (m_label != null) { m_label.MouseEnter += delegate { m_highlight = true; }; m_label.MouseLeave += delegate { m_highlight = false; }; m_label.Click += delegate { UserCheck(); }; } if (innerSize == null) m_innerSize = size; else m_innerSize = innerSize; }
public HslColor(Vector4 v4) { H = v4.X; S = v4.Y; L = v4.Z; A = v4.W; }
public GrassV2zone(List<MaskPixRGB> pixels, Vector4 bounds, int tex = -1) { m_pixels = pixels; m_bounds = bounds; m_textureID = tex; m_texGen = null; }
public Vector4(Vector4 vector) { PointsArray = new double[4]; X = vector.X; Y = vector.Y; Z = vector.Z; }
/// <summary> /// Compresses a position so that its components are between 0 and 1. /// </summary> /// <param name="pos">The position to compress.</param> /// <returns>The compressed position.</returns> public Vector4 CompressPosition(Vector4 pos) { var newX = (pos.X - _info.PositionMinX) / _xScale; var newY = (pos.Y - _info.PositionMinY) / _yScale; var newZ = (pos.Z - _info.PositionMinZ) / _zScale; return new Vector4(newX, newY, newZ, pos.W); }
/// <summary> /// Decompresses a position so that its components are in model space. /// </summary> /// <param name="pos">The position to decompress.</param> /// <returns>The decompressed position.</returns> public Vector4 DecompressPosition(Vector4 pos) { var newX = pos.X * _xScale + _info.PositionMinX; var newY = pos.Y * _yScale + _info.PositionMinY; var newZ = pos.Z * _zScale + _info.PositionMinZ; return new Vector4(newX, newY, newZ, pos.W); }
public BoundingBox Grow(Vector3 change) { var center = new Vector3 { X = (PointA.X + PointB.X) / 2f, Y = (PointA.Y + PointB.Y) / 2f, Z = (PointA.Z + PointB.Z) / 2f }; var d = new Vector3 { X = Math.Abs(PointA.X - center.X) + change.X, Y = Math.Abs(PointA.Y - center.Y) + change.Y, Z = Math.Abs(PointA.Z - center.Z) + change.Z }; var retPointA = new Vector4 { X = center.X + d.X, Y = center.Y + d.Y, Z = center.Z + d.Z, W = PointA.W }; var retPointB = new Vector4 { X = center.X - d.X, Y = center.Y - d.Y, Z = center.Z - d.Z, W = PointB.W }; return new BoundingBox { PointA = retPointA, PointB = retPointB }; }
/// <summary> /// Override PointGeometryModel3D's Attach method to /// provide a buffer of DynamoPointVertices /// </summary> public override void Attach(IRenderHost host) { var techManager = host.RenderTechniquesManager; renderTechnique = techManager.RenderTechniques[DefaultRenderTechniqueNames.Points]; base.Attach(host); if (Geometry == null) return; if (renderHost.RenderTechnique == host.RenderTechniquesManager.RenderTechniques.Get(DeferredRenderTechniqueNames.Deferred) || renderHost.RenderTechnique == host.RenderTechniquesManager.RenderTechniques.Get(DeferredRenderTechniqueNames.Deferred)) return; vertexLayout = host.EffectsManager.GetLayout(renderTechnique); effectTechnique = effect.GetTechniqueByName(renderTechnique.Name); effectTransforms = new EffectTransformVariables(effect); var geometry = Geometry as PointGeometry3D; if (geometry != null) { vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, VertexSizeInBytes, CreateVertexArray()); } vViewport = effect.GetVariableByName("vViewport").AsVector(); vPointParams = effect.GetVariableByName("vPointParams").AsVector(); var pointParams = new Vector4((float)Size.Width, (float)Size.Height, (float)Figure, (float)FigureRatio); vPointParams.Set(pointParams); OnRasterStateChanged(DepthBias); Device.ImmediateContext.Flush(); }
public void Init( Vector4 av4Input ) { maxXAndY.x = av4Input.z; maxXAndY.y = av4Input.w; minXAndY.x = av4Input.x; minXAndY.y = av4Input.y; }
public Vertex(Vector4 position, Color4 color, Vector2 textureCoordinate, uint faceIndex) { Position = position; Color = color; TextureCoordinate = textureCoordinate; FaceIndex = faceIndex; }
public override void DrawShaderGUI(MicroSplatShaderGUI shaderGUI, MicroSplatKeywords keywords, Material mat, MaterialEditor materialEditor, MaterialProperty[] props) { if (MicroSplatUtilities.DrawRollup("Splats")) { var albedoMap = shaderGUI.FindProp("_Diffuse", props); var normalMap = shaderGUI.FindProp("_NormalSAO", props); materialEditor.TexturePropertySingleLine(CAlbedoTex, albedoMap); if (!disableNormals) { if (packMode == TextureArrayConfig.PackingMode.Fastest) { materialEditor.TexturePropertySingleLine(CNormalSpec, normalMap); } else { materialEditor.TexturePropertySingleLine(CNormal, normalMap); } } if (emissiveArray && mat.HasProperty("_EmissiveMetal")) { var emisMap = shaderGUI.FindProp("_EmissiveMetal", props); materialEditor.TexturePropertySingleLine(CEmisMetal, emisMap); if (mat.HasProperty ("_EmissiveMult")) { var emisMult = shaderGUI.FindProp ("_EmissiveMult", props); emisMult.floatValue = EditorGUILayout.Slider (CInterpContrast, emisMult.floatValue, 0.0f, 4.0f); } } if (packMode == TextureArrayConfig.PackingMode.Quality && mat.HasProperty("_SmoothAO")) { var smoothAO = shaderGUI.FindProp("_SmoothAO", props); materialEditor.TexturePropertySingleLine(CSmoothAO, smoothAO); } if (!disableHeightBlend) { var contrastProp = shaderGUI.FindProp("_Contrast", props); contrastProp.floatValue = EditorGUILayout.Slider(CInterpContrast, contrastProp.floatValue, 1.0f, 0.0001f); } if (!keywords.IsKeywordEnabled("_TRIPLANAR")) { EditorGUI.BeginChangeCheck(); Vector4 uvScale = shaderGUI.FindProp("_UVScale", props).vectorValue; Vector2 scl = new Vector2(uvScale.x, uvScale.y); Vector2 offset = new Vector2(uvScale.z, uvScale.w); scl = EditorGUILayout.Vector2Field("Global UV Scale", scl); offset = EditorGUILayout.Vector2Field("Global UV Offset", offset); if (EditorGUI.EndChangeCheck()) { uvScale.x = scl.x; uvScale.y = scl.y; uvScale.z = offset.x; uvScale.w = offset.y; shaderGUI.FindProp("_UVScale", props).vectorValue = uvScale; EditorUtility.SetDirty(mat); } } } }
// Lengyel, Eric. “Computing Tangent Space Basis Vectors for an Arbitrary Mesh”. // Terathon Software 3D Graphics Library, 2001. http://www.terathon.com/code/tangent.html public static void RecalculateTangents(Mesh mesh) { var tan1 = new Vector3[mesh.vertexCount]; var tan2 = new Vector3[mesh.vertexCount]; for (int a = 0; a < mesh.triangles.Length; a += 3) { int i1 = mesh.triangles[a + 0]; int i2 = mesh.triangles[a + 1]; int i3 = mesh.triangles[a + 2]; Vector3 v1 = mesh.vertices[i1]; Vector3 v2 = mesh.vertices[i2]; Vector3 v3 = mesh.vertices[i3]; Vector2 w1 = mesh.uv[i1]; Vector2 w2 = mesh.uv[i2]; Vector2 w3 = mesh.uv[i3]; float x1 = v2.x - v1.x; float x2 = v3.x - v1.x; float y1 = v2.y - v1.y; float y2 = v3.y - v1.y; float z1 = v2.z - v1.z; float z2 = v3.z - v1.z; float s1 = w2.x - w1.x; float s2 = w3.x - w1.x; float t1 = w2.y - w1.y; float t2 = w3.y - w1.y; float r = 1.0F / (s1 * t2 - s2 * t1); var sdir = new Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); var tdir = new Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } var tangents = new Vector4[mesh.vertexCount]; for (long a = 0; a < mesh.vertexCount; a++) { Vector3 n = mesh.normals[a]; Vector3 t = tan1[a]; // Gram-Schmidt orthogonalize tangents[a] = t - n * Vector3.Dot(n, t); tangents[a].Normalize(); // Calculate handedness tangents[a].w = (Vector3.Dot(Vector3.Cross(n, t), tan2[a]) < 0.0f) ? -1.0f : 1.0f; } mesh.tangents = tangents; }
///<summary> /// Input a cubemap, and then prefilter this cubemap for image-based lighting equation. ///</summary> static public void PreFilterEnviromentMap(Cubemap cubemap) { if (cubemap) { int cube_width = cubemap.width; Vector3 vec3 = new Vector3(); // Create a read buffer to store cubemap direction data. ComputeBuffer cubeMatrix = new ComputeBuffer(sgFaceInput.Length, Marshal.SizeOf(vec3)); cubeMatrix.SetData(sgFaceInput); Vector4 vec4 = new Vector4(); // Create a output buffer. ComputeBuffer dstData = new ComputeBuffer(cube_width * cube_width * 6, Marshal.SizeOf(vec4)); ComputeShader CSEnvFilter; CSEnvFilter = (ComputeShader)AssetDatabase.LoadAssetAtPath("Assets/EnvironmentMapTool/ComputeShader/FilterCubeMap.compute", typeof(ComputeShader)); // Set cubemap to shader. CSEnvFilter.SetTexture(0, "gCubemap", cubemap); // Set read write buffer for data output. CSEnvFilter.SetBuffer(0, "gOutput", dstData); // Set cubemap direction data. CSEnvFilter.SetBuffer(0, "sgFace2DMapping", cubeMatrix); Color[] outputData = new Color[cube_width * cube_width * 6]; // How many mipmap level? float mipLevelNum = Mathf.Log(cube_width, 2); // Loop each mipmap level with different roughness. for (int i = 0; i < mipLevelNum + 1; i++) { // The texel number of a face. int image_size = cube_width * cube_width; // The texel number of a cubemap. int num_threads = image_size * 6; // Set roughness value (between 0~1). CSEnvFilter.SetFloat("gRoughness", (i / mipLevelNum)); // The width of a mipmap level of a cube map. CSEnvFilter.SetInt("gWidth", cube_width); // The total number of thread groups (the number of my thread group : 64). num_threads = (int)Mathf.Ceil((float)num_threads / 64.0f); // Run compute shader. CSEnvFilter.Dispatch(0, num_threads, 1, 1); // Get data from the read & write buffer. dstData.GetData(outputData); // Copy data to the original cubemap. SetCubeMipMap(cubemap, outputData, image_size, i); // Half the size for the next mipmap level. cube_width = cube_width / 2; } // Set false to disable auto-generating mipmap. cubemap.Apply(false); // Use trilinear mode to interpolate different mipmap levels. cubemap.filterMode = FilterMode.Trilinear; cubemap.wrapMode = TextureWrapMode.Clamp; cubemap.name = cubemap.name + "(PreFilter)"; // Release data. dstData.Release(); cubeMatrix.Release(); } }
private bool SetShaderParameters(DeviceContext deviceContext, Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix, Vector4 apexColour, Vector4 centerColor) { // Transpose the matrices to prepare them for the shader. worldMatrix.Transpose(); viewMatrix.Transpose(); projectionMatrix.Transpose(); // Lock the constant buffer so it can be written to. DataStream mappedResource; deviceContext.MapSubresource(ConstantMatrixBuffer, MapMode.WriteDiscard, MapFlags.None, out mappedResource); // Copy the matrices into the constant buffer. DMatrixBuffer matrixBuffer = new DMatrixBuffer() { world = worldMatrix, view = viewMatrix, projection = projectionMatrix }; mappedResource.Write(matrixBuffer); // Unlock the constant buffer. deviceContext.UnmapSubresource(ConstantMatrixBuffer, 0); // Set the position of the constant buffer in the vertex shader. int bufferNumber = 0; // Finally set the constant buffer in the vertex shader with the updated values. deviceContext.VertexShader.SetConstantBuffer(bufferNumber, ConstantMatrixBuffer); // Lock the gradient constant buffer so it can be written to. deviceContext.MapSubresource(ConstantGradientBuffer, MapMode.WriteDiscard, MapFlags.None, out mappedResource); // Copy the gradient color variables into the constant buffer. DGradientBuffer gradientBuffer = new DGradientBuffer() { apexColor = apexColour, centerColor = centerColor }; mappedResource.Write(gradientBuffer); // Unlock the constant buffer. deviceContext.UnmapSubresource(ConstantGradientBuffer, 0); // Set the position of the gradient constant buffer in the pixel shader. bufferNumber = 0; // Finally set the gradient constant buffer in the pixel shader with the updated values. deviceContext.PixelShader.SetConstantBuffer(bufferNumber, ConstantGradientBuffer); return(true); }
public bool Render(DeviceContext deviceContext, int indexCount, Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix, Vector4 apexColour, Vector4 centerColor) { // Set the shader parameters that it will use for rendering. if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, apexColour, centerColor)) { return(false); } // Now render the prepared buffers with the shader. RenderShader(deviceContext, indexCount); return(true); }
protected Quaternion Vector4ToQuaternion(Vector4 rot) { return(new Quaternion(rot.x, rot.y, rot.z, rot.w)); }
public static Pos ToPos(this Vector4 v) { return(new Pos(v.X, v.Y, v.Z, v.W)); }
public void PackFromVector4(Vector4 vector) { this.PackedValue = Pack(vector.X, vector.Y, vector.Z, vector.W); }
/// <summary> /// Gets the Brush Element Attributes from the Match /// </summary> /// <param name="match">Match object</param> protected override void GetAttributes(Match match) { float centerX, centerY; // RadiusX Single.TryParse(match.Groups["RadiusX"].Value, out _radiusX); // Sanitize by taking the absolute value _radiusX = Math.Abs(_radiusX); // RadiusY Single.TryParse(match.Groups["RadiusY"].Value, out _radiusY); // Sanitize by taking the absolute value _radiusY = Math.Abs(_radiusY); // CenterX Single.TryParse(match.Groups["CenterX"].Value, out centerX); // CenterY Single.TryParse(match.Groups["CenterY"].Value, out centerY); _center = new Vector2(centerX, centerY); // Opacity (optional) var group = match.Groups["Opacity"]; if (group.Success) { Single.TryParse(group.Value, out _opacity); } // Origin Offset (optional) group = match.Groups["OriginOffset"]; if (group.Success) { float offsetX, offsetY; Single.TryParse(match.Groups["OffsetX"].Value, out offsetX); Single.TryParse(match.Groups["OffsetY"].Value, out offsetY); _originOffset = new Vector2(offsetX, offsetY); } // Alpha Mode (optional) group = match.Groups["AlphaMode"]; if (group.Success) { Enum.TryParse(group.Value, out _alphaMode); } // Buffer Precision (optional) group = match.Groups["BufferPrecision"]; if (group.Success) { Enum.TryParse(group.Value, out _bufferPrecision); } // Edge Behavior (optional) group = match.Groups["EdgeBehavior"]; if (group.Success) { Enum.TryParse(group.Value, out _edgeBehavior); } // Pre Interpolation ColorSpace (optional) group = match.Groups["PreColorSpace"]; if (group.Success) { Enum.TryParse(group.Value, out _preInterpolationColorSpace); } // Post Interpolation ColorSpace (optional) group = match.Groups["PostColorSpace"]; if (group.Success) { Enum.TryParse(group.Value, out _postInterpolationColorSpace); } // GradientStopHdrs group = match.Groups["GradientStops"]; if (group.Success) { _gradientStopHdrs.Clear(); foreach (Capture capture in group.Captures) { var gradientMatch = RegexFactory.GradientStopHdrRegex.Match(capture.Value); if (!gradientMatch.Success) { continue; } float position; float x = 0, y = 0, z = 0, w = 0; var main = gradientMatch.Groups["Main"]; if (main.Success) { var mainMatch = RegexFactory.GetAttributesRegex(GradientStopAttributeType.MainHdr) .Match(main.Value); Single.TryParse(mainMatch.Groups["Position"].Value, out position); Single.TryParse(mainMatch.Groups["X"].Value, out x); Single.TryParse(mainMatch.Groups["Y"].Value, out y); Single.TryParse(mainMatch.Groups["Z"].Value, out z); Single.TryParse(mainMatch.Groups["W"].Value, out w); var color = new Vector4(x, y, z, w); _gradientStopHdrs.Add(new CanvasGradientStopHdr() { Color = color, Position = position }); } var additional = gradientMatch.Groups["Additional"]; if (!additional.Success) { continue; } foreach (Capture addCapture in additional.Captures) { var addMatch = RegexFactory.GetAttributesRegex(GradientStopAttributeType.AdditionalHdr) .Match(addCapture.Value); Single.TryParse(addMatch.Groups["Position"].Value, out position); Single.TryParse(addMatch.Groups["X"].Value, out x); Single.TryParse(addMatch.Groups["Y"].Value, out y); Single.TryParse(addMatch.Groups["Z"].Value, out z); Single.TryParse(addMatch.Groups["W"].Value, out w); var color = new Vector4(x, y, z, w); _gradientStopHdrs.Add(new CanvasGradientStopHdr() { Color = color, Position = position }); } } // Sort the stops based on their position if (_gradientStopHdrs.Any()) { _gradientStopHdrs = _gradientStopHdrs.OrderBy(g => g.Position).ToList(); } } }
public void Build(List <Plane3D> Faces) { Generate(); Mode = Gl.GL_TRIANGLES; NumOfPrim = Faces.Count; int[] Elements = new int[NumOfPrim * 3]; float[] Vertex = new float[NumOfPrim * 9]; float[] Normals = new float[NumOfPrim * 9]; float[] Colors = new float[NumOfPrim * 12]; float[] TexCoords = new float[NumOfPrim * 6]; for (int j = 0; j < NumOfPrim; ++j) { int j3 = j * 3; int j9 = j * 9; int j6 = j * 6; int j12 = j * 12; Elements[j3 + 0] = j3; Elements[j3 + 1] = j3 + 1; Elements[j3 + 2] = j3 + 2; Vertex[j9 + 0] = (float)Faces[j].Vertex[0].X; Vertex[j9 + 1] = (float)Faces[j].Vertex[0].Y; Vertex[j9 + 2] = (float)Faces[j].Vertex[0].Z; Vertex[j9 + 3] = (float)Faces[j].Vertex[1].X; Vertex[j9 + 4] = (float)Faces[j].Vertex[1].Y; Vertex[j9 + 5] = (float)Faces[j].Vertex[1].Z; Vertex[j9 + 6] = (float)Faces[j].Vertex[2].X; Vertex[j9 + 7] = (float)Faces[j].Vertex[2].Y; Vertex[j9 + 8] = (float)Faces[j].Vertex[2].Z; Normals[j9 + 0] = (float)Faces[j].Normals[0].X; Normals[j9 + 1] = (float)Faces[j].Normals[0].Y; Normals[j9 + 2] = (float)Faces[j].Normals[0].Z; Normals[j9 + 3] = (float)Faces[j].Normals[1].X; Normals[j9 + 4] = (float)Faces[j].Normals[1].Y; Normals[j9 + 5] = (float)Faces[j].Normals[1].Z; Normals[j9 + 6] = (float)Faces[j].Normals[2].X; Normals[j9 + 7] = (float)Faces[j].Normals[2].Y; Normals[j9 + 8] = (float)Faces[j].Normals[2].Z; TexCoords[j6 + 0] = (float)Faces[j].TextureUV[0].X; TexCoords[j6 + 1] = (float)Faces[j].TextureUV[0].Y; TexCoords[j6 + 2] = (float)Faces[j].TextureUV[1].X; TexCoords[j6 + 3] = (float)Faces[j].TextureUV[1].Y; TexCoords[j6 + 4] = (float)Faces[j].TextureUV[2].X; TexCoords[j6 + 5] = (float)Faces[j].TextureUV[2].Y; Vector4 Col = Colorized ? Vector4.PerComponentProduct(Faces[j].Color, MyColor) : Faces[j].Color; Colors[j12 + 0] = (float)Col.X; Colors[j12 + 1] = (float)Col.Y; Colors[j12 + 2] = (float)Col.Z; Colors[j12 + 3] = (float)Col.A; Colors[j12 + 4] = (float)Col.X; Colors[j12 + 5] = (float)Col.Y; Colors[j12 + 6] = (float)Col.Z; Colors[j12 + 7] = (float)Col.A; Colors[j12 + 8] = (float)Col.X; Colors[j12 + 9] = (float)Col.Y; Colors[j12 + 10] = (float)Col.Z; Colors[j12 + 11] = (float)Col.A; } int DynCap = Gl.GL_STATIC_DRAW; Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, bufs[VertexIndex]); Gl.glBufferData(Gl.GL_ARRAY_BUFFER, (IntPtr)(Vertex.Length * sizeof(float)), Vertex, DynCap); Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, bufs[NormalIndex]); Gl.glBufferData(Gl.GL_ARRAY_BUFFER, (IntPtr)(Normals.Length * sizeof(float)), Normals, DynCap); Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, bufs[ColorIndex]); Gl.glBufferData(Gl.GL_ARRAY_BUFFER, (IntPtr)(Colors.Length * sizeof(float)), Colors, DynCap); Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, bufs[TextureIndex]); Gl.glBufferData(Gl.GL_ARRAY_BUFFER, (IntPtr)(TexCoords.Length * sizeof(float)), TexCoords, DynCap); Gl.glBindBuffer(Gl.GL_ELEMENT_ARRAY_BUFFER, bufs[PrimitiveIndex]); Gl.glBufferData(Gl.GL_ELEMENT_ARRAY_BUFFER, (IntPtr)(Elements.Length * sizeof(int)), Elements, DynCap); Utils.AssertGLError("build - bind VBO-s"); /* Colors = null; * Vertex = null; * Normals = null; * Elements = null; * TexCoords = null;*/ }
/// <summary> /// Initializes a new instance of the <see cref="Bgra5551"/> struct. /// </summary> /// <param name="vector"> /// The vector containing the components for the packed vector. /// </param> public Bgra5551(Vector4 vector) { this.PackedValue = Pack(vector.X, vector.Y, vector.Z, vector.W); }
public void Write(Vector4 value) => this.WriteVector4(value);
public void Colorizer(bool Enable, Vector4 MyColor) { Colorized = Enable; this.MyColor = MyColor; }
protected abstract void InitLight(MyLight light, Vector4 color, float radius, float falloff);
private void RenderReflectionFor(Camera cam, Camera reflectCamera) { if (!reflectCamera) { return; } if (sharedMaterial && !sharedMaterial.HasProperty(reflectionSampler)) { return; } reflectCamera.cullingMask = reflectionMask & ~(1 << LayerMask.NameToLayer("Water")); SaneCameraSettings(reflectCamera); reflectCamera.backgroundColor = clearColor; reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor; if (reflectSkybox) { if (cam.gameObject.GetComponent(typeof(Skybox))) { Skybox sb = (Skybox)reflectCamera.gameObject.GetComponent(typeof(Skybox)); if (!sb) { sb = (Skybox)reflectCamera.gameObject.AddComponent(typeof(Skybox)); } sb.material = ((Skybox)cam.GetComponent(typeof(Skybox))).material; } } var oldCulling = GL.invertCulling; GL.invertCulling = !GL.invertCulling; Transform reflectiveSurface = transform; //waterHeight; Vector3 eulerA = cam.transform.eulerAngles; reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z); reflectCamera.transform.position = cam.transform.position; Vector3 pos = reflectiveSurface.transform.position; pos.y = reflectiveSurface.position.y; Vector3 normal = reflectiveSurface.transform.up; float d = -Vector3.Dot(normal, pos) - clipPlaneOffset; Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d); Matrix4x4 reflection = Matrix4x4.zero; reflection = CalculateReflectionMatrix(reflection, reflectionPlane); oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint(oldpos); reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f); reflectCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane); reflectCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z); reflectCamera.Render(); GL.invertCulling = oldCulling; }
public static void CrossProduct4D_Theory(Vector128 <float> left, Vector128 <float> right, Vector128 <float> third, Vector4 expected) { Vector128 <float> result = Vector.CrossProduct4D(left, right, third); Assert.True(AreEqual(expected, result), $"Expected {expected}, got {result}"); }
public override void Init(MyObjectBuilder_CubeBlock objectBuilder, MyCubeGrid cubeGrid) { var sinkComp = new MyResourceSinkComponent(); sinkComp.Init( BlockDefinition.ResourceSinkGroup, BlockDefinition.RequiredPowerInput, () => (Enabled && IsFunctional) ? ResourceSink.MaxRequiredInput : 0f); sinkComp.IsPoweredChanged += Receiver_IsPoweredChanged; ResourceSink = sinkComp; base.Init(objectBuilder, cubeGrid); this.IsLargeLight = cubeGrid.GridSizeEnum == MyCubeSize.Large; var builder = (MyObjectBuilder_LightingBlock)objectBuilder; MyModel lightModel = VRage.Game.Models.MyModels.GetModelOnlyDummies(BlockDefinition.Model); foreach (var pair in lightModel.Dummies) { if (!pair.Key.ToLower().Contains("light")) { continue; } m_lightLocalPosition = pair.Value.Matrix.Translation; break; } Vector4 color = (builder.ColorAlpha == -1) ? LightColorDef : new Vector4(builder.ColorRed, builder.ColorGreen, builder.ColorBlue, builder.ColorAlpha); float radius = RadiusBounds.Clamp((builder.Radius == -1f) ? RadiusBounds.Default : builder.Radius); float reflectorRadius = ReflectorRadiusBounds.Clamp((builder.ReflectorRadius == -1f) ? ReflectorRadiusBounds.Default : builder.ReflectorRadius); float falloff = FalloffBounds.Clamp(builder.Falloff); m_blinkIntervalSeconds.Value = BlinkIntervalSecondsBounds.Clamp((builder.BlinkIntervalSeconds == -1f) ? BlinkIntervalSecondsBounds.Default : builder.BlinkIntervalSeconds); m_blinkLength.Value = BlinkLenghtBounds.Clamp((builder.BlinkLenght == -1f) ? BlinkLenghtBounds.Default : builder.BlinkLenght); m_blinkOffset.Value = BlinkOffsetBounds.Clamp((builder.BlinkOffset == -1f) ? BlinkOffsetBounds.Default : builder.BlinkOffset); m_intesity.Value = IntensityBounds.Clamp((builder.Intensity == -1f) ? IntensityBounds.Default : builder.Intensity); m_positionDirty = true; m_light = MyLights.AddLight(); InitLight(m_light, color, radius, falloff); m_light.ReflectorRange = reflectorRadius; m_light.Range = radius; m_light.ReflectorOn = false; m_light.LightOn = false; m_light.GlareOn = false; UpdateIntensity(); UpdateLightPosition(); NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME | MyEntityUpdateEnum.BEFORE_NEXT_FRAME | MyEntityUpdateEnum.EACH_100TH_FRAME; Render.NeedsDrawFromParent = true; AddDebugRenderComponent(new MyDebugRenderComponentDrawPowerReciever(ResourceSink, this)); ResourceSink.Update(); SlimBlock.ComponentStack.IsFunctionalChanged += ComponentStack_IsFunctionalChanged; IsWorkingChanged += CubeBlock_OnWorkingChanged; }
void Update () { if (mAnim != null && mAnim.isPlaying) return; if (style != Style.None) { float adjustment = 1f; if (panelContainer != null) { if (panelContainer.clipping == UIDrawCall.Clipping.None) { // Panel has no clipping -- just use the screen's dimensions mRect.xMin = -Screen.width * 0.5f; mRect.yMin = -Screen.height * 0.5f; mRect.xMax = -mRect.xMin; mRect.yMax = -mRect.yMin; } else { // Panel has clipping -- use it as the rect Vector4 pos = panelContainer.clipRange; mRect.x = pos.x - (pos.z * 0.5f); mRect.y = pos.y - (pos.w * 0.5f); mRect.width = pos.z; mRect.height = pos.w; } } else if (widgetContainer != null) { // Widget is used -- use its bounds as the container's bounds Transform t = widgetContainer.cachedTransform; Vector3 ls = t.localScale; Vector3 lp = t.localPosition; Vector3 size = widgetContainer.relativeSize; Vector3 offset = widgetContainer.pivotOffset; offset.y -= 1f; offset.x *= (widgetContainer.relativeSize.x * ls.x); offset.y *= (widgetContainer.relativeSize.y * ls.y); mRect.x = lp.x + offset.x; mRect.y = lp.y + offset.y; mRect.width = size.x * ls.x; mRect.height = size.y * ls.y; } else if (uiCamera != null) { mRect = uiCamera.pixelRect; if (mRoot != null) adjustment = mRoot.pixelSizeAdjustment; } else return; float rectWidth = mRect.width; float rectHeight = mRect.height; if (adjustment != 1f && rectHeight > 1f) { float scale = mRoot.activeHeight / rectHeight; rectWidth *= scale; rectHeight *= scale; } Vector3 localScale = mTrans.localScale; if (style == Style.BasedOnHeight) { localScale.x = relativeSize.x * rectHeight; localScale.y = relativeSize.y * rectHeight; } else if (style == Style.FillKeepingRatio) { // Contributed by Dylan Ryan float screenRatio = rectWidth / rectHeight; float imageRatio = initialSize.x / initialSize.y; if (imageRatio < screenRatio) { // Fit horizontally float scale = rectWidth / initialSize.x; localScale.x = rectWidth; localScale.y = initialSize.y * scale; } else { // Fit vertically float scale = rectHeight / initialSize.y; localScale.x = initialSize.x * scale; localScale.y = rectHeight; } } else if (style == Style.FitInternalKeepingRatio) { // Contributed by Dylan Ryan float screenRatio = rectWidth / rectHeight; float imageRatio = initialSize.x / initialSize.y; if (imageRatio > screenRatio) { // Fit horizontally float scale = rectWidth / initialSize.x; localScale.x = rectWidth; localScale.y = initialSize.y * scale; } else { // Fit vertically float scale = rectHeight / initialSize.y; localScale.x = initialSize.x * scale; localScale.y = rectHeight; } } else { if (style == Style.Both || style == Style.Horizontal) localScale.x = relativeSize.x * rectWidth; if (style == Style.Both || style == Style.Vertical) localScale.y = relativeSize.y * rectHeight; } if (mTrans.localScale != localScale) mTrans.localScale = localScale; if (runOnlyOnce && Application.isPlaying) Destroy(this); } }
private void ErodeHelper(Vector3 terrainScale, Rect domainRect, Vector2 texelSize, bool invertEffect, bool lowRes) { RenderTexture tmpRT = UnityEngine.RenderTexture.active; //this one is mandatory if (!inputTextures.ContainsKey("Height")) { throw (new Exception("No input heightfield specified!")); } #region Find Compute Kernels ComputeShader advectionCS = GetComputeShader("Advection"); ComputeShader projectionCS = GetComputeShader("Projection"); ComputeShader diffusionCS = GetComputeShader("Diffusion"); ComputeShader utilityCS = GetComputeShader("ImageUtility"); ComputeShader aeolianCS = GetComputeShader("Aeolian"); ComputeShader thermalCS = GetComputeShader("Thermal"); int advectKernelIdx = advectionCS.FindKernel("Advect"); int divergenceKernelIdx = projectionCS.FindKernel("Divergence"); int gradientSubtractKernelIdx = projectionCS.FindKernel("GradientSubtract"); int diffuseKernelIdx = diffusionCS.FindKernel("Diffuse"); int remapKernelIdx = utilityCS.FindKernel("RemapValues"); int addConstantIdx = utilityCS.FindKernel("AddConstant"); int applyDragKernelIdx = aeolianCS.FindKernel("ApplyHeightfieldDrag"); int erodeKernelIdx = aeolianCS.FindKernel("WindSedimentErode"); int thermalKernelIdx = thermalCS.FindKernel("ThermalErosion"); int[] numWorkGroups = { 8, 8, 1 }; #endregion #region Calculate Domain Rect Size //figure out what size we need our render targets to be int xRes = (int)inputTextures["Height"].width; int yRes = (int)inputTextures["Height"].height; int rx = xRes - (numWorkGroups[0] * (xRes / numWorkGroups[0])); int ry = yRes - (numWorkGroups[1] * (yRes / numWorkGroups[1])); xRes += numWorkGroups[0] - rx; yRes += numWorkGroups[1] - ry; #endregion #region Create Render Textures RenderTexture heightmapRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture heightmapPrevRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture collisionRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture sedimentPrevRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture sedimentRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture windVelRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RGFloat, RenderTextureReadWrite.Linear); RenderTexture windVelPrevRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RGFloat, RenderTextureReadWrite.Linear); RenderTexture divergenceRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); RenderTexture thermalSedimentRT = RenderTexture.GetTemporary(xRes, yRes, 0, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear); heightmapRT.enableRandomWrite = true; heightmapPrevRT.enableRandomWrite = true; collisionRT.enableRandomWrite = true; sedimentRT.enableRandomWrite = true; sedimentPrevRT.enableRandomWrite = true; windVelRT.enableRandomWrite = true; windVelPrevRT.enableRandomWrite = true; divergenceRT.enableRandomWrite = true; thermalSedimentRT.enableRandomWrite = true; #endregion #region Setup Input Textures //clear the render textures Graphics.Blit(Texture2D.blackTexture, sedimentRT); Graphics.Blit(Texture2D.blackTexture, collisionRT); Graphics.Blit(Texture2D.blackTexture, windVelRT); Graphics.Blit(Texture2D.blackTexture, windVelPrevRT); Graphics.Blit(inputTextures["Height"], heightmapPrevRT); Graphics.Blit(inputTextures["Height"], heightmapRT); #endregion //precompute some values on the CPU (these become uniform constants in the shader) float dx = (float)texelSize.x * m_SimulationScale.value; float dy = (float)texelSize.y * m_SimulationScale.value; float dxy = Mathf.Sqrt(dx * dx + dy * dy); float gridScale = 0.5f * dx; Vector4 dxdy = new Vector4(dx, dy, dxy, gridScale); advectionCS.SetFloat("dt", m_dt.value); advectionCS.SetFloat("velScale", m_AdvectionVelScale.value); advectionCS.SetVector("dxdy", dxdy); advectionCS.SetVector("terrainDim", new Vector4()); advectionCS.SetVector("texDim", new Vector4((float)xRes, (float)yRes, 0.0f, 0.0f)); diffusionCS.SetFloat("dt", m_dt.value); projectionCS.SetVector("dxdy", dxdy); aeolianCS.SetFloat("dt", m_dt.value); aeolianCS.SetFloat("SuspensionRate", m_SuspensionRate.value); aeolianCS.SetFloat("DepositionRate", m_DepositionRate.value); aeolianCS.SetFloat("SlopeFactor", m_SlopeFactor.value); aeolianCS.SetFloat("DragCoefficient", m_DragCoefficient.value); aeolianCS.SetFloat("ReflectionCoefficient", m_ReflectionCoefficient.value); aeolianCS.SetFloat("AbrasivenessCoefficient", m_AbrasivenessCoefficient.value * 1000.0f); aeolianCS.SetVector("texDim", new Vector4((float)xRes, (float)yRes, 0.0f, 0.0f)); //use full tile res here? diffusionCS.SetVector("texDim", new Vector4((float)inputTextures["Height"].width, (float)inputTextures["Height"].height, 0.0f, 0.0f)); #region Fluid Simulation Loop for (int i = 0; i < m_Iterations.value; i++) { #region Velocity Step utilityCS.SetTexture(addConstantIdx, "OutputTex", windVelPrevRT); utilityCS.SetVector("Constant", m_WindVel); utilityCS.Dispatch(addConstantIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); //Apply drag from heightfield aeolianCS.SetTexture(applyDragKernelIdx, "InHeightMap", heightmapPrevRT); aeolianCS.SetTexture(applyDragKernelIdx, "WindVel", windVelPrevRT); aeolianCS.SetTexture(applyDragKernelIdx, "OutWindVel", windVelRT); aeolianCS.Dispatch(applyDragKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); //Diffuse Velocity diffusionCS.SetFloat("diff", m_Viscosity.value); for (int j = 0; j < m_DiffuseSteps; j++) { diffusionCS.SetTexture(diffuseKernelIdx, "InputTex", windVelRT); diffusionCS.SetTexture(diffuseKernelIdx, "OutputTex", windVelPrevRT); diffusionCS.Dispatch(diffuseKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); Graphics.Blit(windVelPrevRT, windVelRT); } //Project Velocity for (int j = 0; j < m_ProjectionSteps; j++) { projectionCS.SetTexture(divergenceKernelIdx, "VelocityTex2D", windVelRT); projectionCS.SetTexture(divergenceKernelIdx, "DivergenceTex2D", divergenceRT); projectionCS.Dispatch(divergenceKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); projectionCS.SetTexture(gradientSubtractKernelIdx, "PressureTex2D", divergenceRT); projectionCS.SetTexture(gradientSubtractKernelIdx, "VelocityTex2D", windVelRT); projectionCS.SetTexture(gradientSubtractKernelIdx, "VelocityOutTex2D", windVelPrevRT); projectionCS.Dispatch(gradientSubtractKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); Graphics.Blit(windVelPrevRT, windVelRT); } //Advect velocity along previous iteration's velocity field advectionCS.SetTexture(advectKernelIdx, "InputTex", windVelRT); advectionCS.SetTexture(advectKernelIdx, "OutputTex", windVelPrevRT); advectionCS.SetTexture(advectKernelIdx, "VelocityTex", windVelRT); advectionCS.Dispatch(advectKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); Graphics.Blit(windVelPrevRT, windVelRT); #endregion #region Density Step //Diffuse Sediment diffusionCS.SetFloat("diff", m_DiffusionRate.value); for (int j = 0; j < m_DiffuseSteps; j++) { diffusionCS.SetTexture(diffuseKernelIdx, "InputTex", sedimentRT); diffusionCS.SetTexture(diffuseKernelIdx, "OutputTex", sedimentPrevRT); diffusionCS.Dispatch(diffuseKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); Graphics.Blit(sedimentPrevRT, sedimentRT); } //Advect Sediment advectionCS.SetTexture(advectKernelIdx, "InputTexFloat", sedimentRT); advectionCS.SetTexture(advectKernelIdx, "OutputTexFloat", sedimentPrevRT); advectionCS.SetTexture(advectKernelIdx, "VelocityTex", windVelRT); advectionCS.Dispatch(advectKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); #endregion #region Erosion Step // Erode Sediment (pick sediment up off the heightmap and store in sediment RT) aeolianCS.SetTexture(erodeKernelIdx, "InHeightMap", heightmapPrevRT); aeolianCS.SetTexture(erodeKernelIdx, "InSediment", sedimentPrevRT); aeolianCS.SetTexture(erodeKernelIdx, "WindVel", windVelRT); aeolianCS.SetTexture(erodeKernelIdx, "OutSediment", sedimentRT); aeolianCS.SetTexture(erodeKernelIdx, "OutHeightMap", heightmapRT); aeolianCS.Dispatch(erodeKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); #endregion #region Thermal / Diffusion thermalCS.SetFloat("dt", m_ThermalTimeDelta.value * m_dt.value); thermalCS.SetVector("dxdy", dxdy); thermalCS.SetVector("terrainDim", new Vector4(terrainScale.x, terrainScale.y, terrainScale.z)); thermalCS.SetVector("texDim", new Vector4((float)xRes, (float)yRes, 0.0f, 0.0f)); thermalCS.SetTexture(thermalKernelIdx, "TerrainHeightPrev", heightmapPrevRT); thermalCS.SetTexture(thermalKernelIdx, "TerrainHeight", heightmapRT); thermalCS.SetTexture(thermalKernelIdx, "Sediment", thermalSedimentRT); thermalCS.SetTexture(thermalKernelIdx, "ReposeMask", collisionRT); //TODO thermalCS.SetTexture(thermalKernelIdx, "Collision", collisionRT); thermalCS.SetTexture(thermalKernelIdx, "Hardness", collisionRT); //TODO Graphics.Blit(heightmapRT, heightmapPrevRT); for (int j = 0; j < m_ThermalIterations; j++) { Vector2 m = new Vector2(Mathf.Tan(m_AngleOfRepose * Mathf.Deg2Rad), Mathf.Tan(m_AngleOfRepose * Mathf.Deg2Rad)); thermalCS.SetVector("angleOfRepose", new Vector4(m.x, m.y, 0.0f, 0.0f)); thermalCS.Dispatch(thermalKernelIdx, xRes / numWorkGroups[0], yRes / numWorkGroups[1], numWorkGroups[2]); Graphics.Blit(heightmapRT, heightmapPrevRT); } #endregion //swap buffers for next iteration //Graphics.Blit(heightmapRT, heightmapPrevRT); Graphics.Blit(sedimentRT, sedimentPrevRT); } #endregion Graphics.Blit(heightmapRT, outputTextures["Height"]); Graphics.Blit(windVelRT, outputTextures["Wind Velocity"]); Graphics.Blit(divergenceRT, outputTextures["Divergence"]); Graphics.Blit(thermalSedimentRT, outputTextures["Thermal Sediment"]); Graphics.Blit(sedimentRT, outputTextures["Sediment"]); RenderTexture.ReleaseTemporary(heightmapRT); RenderTexture.ReleaseTemporary(heightmapPrevRT); RenderTexture.ReleaseTemporary(collisionRT); RenderTexture.ReleaseTemporary(sedimentRT); RenderTexture.ReleaseTemporary(sedimentPrevRT); RenderTexture.ReleaseTemporary(windVelRT); RenderTexture.ReleaseTemporary(windVelPrevRT); RenderTexture.ReleaseTemporary(divergenceRT); RenderTexture.ReleaseTemporary(thermalSedimentRT); UnityEngine.RenderTexture.active = tmpRT; }
private void CreateVertexBuffer(Device device) { _vertices = new VertexDefinition.PositionTextureColor[_numberOfLetters * 4]; int letterIndex = 0; Color color = BaseColor; int lineHeight = Font.Characters.First().Value.height; float spaceSize = SpaceSize; float positionY = Padding.Top; if (VerticalAlignment == VerticalAlignment.Bottom) { positionY = Size.Y - (lineHeight * Lines.Count + LineSpacing * (Lines.Count - 1)) - Padding.Bottom; } if (VerticalAlignment == VerticalAlignment.Middle) { positionY = Padding.Top + (float)(Size.Y - Padding.Bottom - Padding.Top - (lineHeight * Lines.Count + LineSpacing * (Lines.Count - 1))) / 2; } for (int i = 0; i < Lines.Count; i++) { TextLine line = Lines[i]; line.Width -= SpaceSize + 1; //Remove last space and pixel padding after last character float positionX = Padding.Left; if (HorizontalAlignment == HorizontalAlignment.Right) { positionX = Size.X - line.Width - Padding.Right; } if (HorizontalAlignment == HorizontalAlignment.Center) { positionX = Padding.Left + (float)(Size.X - Padding.Left - Padding.Right - line.Width) / 2; } if (HorizontalAlignment == HorizontalAlignment.Justify && line.WordWrapped) { spaceSize = SpaceSize + (float)(Size.X - Padding.Left - Padding.Right - line.Width) / (line.WordCount - 1); } for (int j = 0; j < line.Words.Count; j++) { string word = line.Words[j]; for (int k = 0; k < word.Length; k++) { char letter = word[k]; if (letter == '[') { if (word[k + 1] != '[') { string token = word.Substring(k + 1, word.IndexOf(']', k + 1) - (k + 1)); if (token == "-") { color = BaseColor; } else if (!ColorParser.TryParse(token, out color)) { throw new InvalidOperationException("Unexpected token : " + token); } k = word.IndexOf(']', k + 1); continue; } k++; } Vector4 colorAsVector = color.ToVector4(); Font.Character c = Font.Characters[letter]; _vertices[letterIndex * 4] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX, positionY, 0.0f), texture = new Vector2(c.uLeft, c.vTop), color = colorAsVector }; //Top left _vertices[letterIndex * 4 + 1] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX + c.width, positionY + c.height, 0.0f), texture = new Vector2(c.uRight, c.vBottom), color = colorAsVector }; //Right bottom _vertices[letterIndex * 4 + 2] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX, positionY + c.height, 0.0f), texture = new Vector2(c.uLeft, c.vBottom), color = colorAsVector }; //Left bottom _vertices[letterIndex * 4 + 3] = new VertexDefinition.PositionTextureColor { position = new Vector3(positionX + c.width, positionY, 0.0f), texture = new Vector2(c.uRight, c.vTop), color = colorAsVector }; //Top right positionX += c.width + 1; letterIndex++; } positionX += spaceSize; } positionY += lineHeight + LineSpacing; } if (_vertexBuffer != null) { _vertexBuffer.Dispose(); } _vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, _vertices); UsedSize = new Vector2I(Lines.Max(l => l.Width) + Padding.Left + Padding.Right, (lineHeight * Lines.Count + LineSpacing * (Lines.Count - 1)) + Padding.Bottom + Padding.Top); }
protected override void Init(MyObjectBuilder_DefinitionBase builder) { base.Init(builder); var ob = builder as MyObjectBuilder_HandItemDefinition; MyDebug.AssertDebug(ob != null); Id = builder.Id; LeftHand = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.LeftHandOrientation)); LeftHand.Translation = ob.LeftHandPosition; RightHand = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.RightHandOrientation)); RightHand.Translation = ob.RightHandPosition; ItemLocation = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.ItemOrientation)); ItemLocation.Translation = ob.ItemPosition; ItemWalkingLocation = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.ItemWalkingOrientation)); ItemWalkingLocation.Translation = ob.ItemWalkingPosition; BlendTime = ob.BlendTime; XAmplitudeOffset = ob.XAmplitudeOffset; YAmplitudeOffset = ob.YAmplitudeOffset; ZAmplitudeOffset = ob.ZAmplitudeOffset; XAmplitudeScale = ob.XAmplitudeScale; YAmplitudeScale = ob.YAmplitudeScale; ZAmplitudeScale = ob.ZAmplitudeScale; RunMultiplier = ob.RunMultiplier; ItemLocation3rd = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.ItemOrientation3rd)); ItemLocation3rd.Translation = ob.ItemPosition3rd; ItemWalkingLocation3rd = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.ItemWalkingOrientation3rd)); ItemWalkingLocation3rd.Translation = ob.ItemWalkingPosition3rd; AmplitudeMultiplier3rd = ob.AmplitudeMultiplier3rd; SimulateLeftHand = ob.SimulateLeftHand; SimulateRightHand = ob.SimulateRightHand; FingersAnimation = MyDefinitionManager.Static.GetAnimationDefinitionCompatibility(ob.FingersAnimation); ItemShootLocation = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.ItemShootOrientation)); ItemShootLocation.Translation = ob.ItemShootPosition; ItemShootLocation3rd = Matrix.CreateFromQuaternion(Quaternion.Normalize(ob.ItemShootOrientation3rd)); ItemShootLocation3rd.Translation = ob.ItemShootPosition3rd; ShootBlend = ob.ShootBlend; MuzzlePosition = ob.MuzzlePosition; ShootScatter = ob.ShootScatter; ScatterSpeed = ob.ScatterSpeed; PhysicalItemId = ob.PhysicalItemId; LightColor = ob.LightColor; LightFalloff = ob.LightFalloff; LightRadius = ob.LightRadius; LightGlareSize = ob.LightGlareSize; LightIntensityLower = ob.LightIntensityLower; LightIntensityUpper = ob.LightIntensityUpper; ShakeAmountTarget = ob.ShakeAmountTarget; ShakeAmountNoTarget = ob.ShakeAmountNoTarget; }
public MarkupStyleMesh() { Scale = new Vector4(0.5f / MeshHalfWidth, 0.5f / MeshHalfLength, 1f, 1f); }
private Mesh CreateStarfieldMesh() { const int numberOfStars = 9110; var binaryDataFile = Resources.Load("Binary/Stars", typeof(TextAsset)) as TextAsset; if (binaryDataFile == null) { Debug.Log("Starfield: Binary data file reading error!"); return(null); } var starsCIs = new List <CombineInstance>(); using (var reader = new BinaryReader(new MemoryStream(binaryDataFile.bytes))) { for (int i = 0; i < numberOfStars - 1; i++) { var star = new StarfieldStar(); var starSize = StarsDistance / 100 * StarsScale; // NOTE : Swap Z and Y... star.Position = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); star.Color = new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), 0); star.Position = Vector3.Scale(star.Position, new Vector3(-1.0f, 1.0f, -1.0f)); star.Color.w = new Vector3(star.Color.x, star.Color.y, star.Color.z).magnitude; if (star.Color.w > 5.7f) { star.Color = Vector4.Normalize(star.Color) * 0.5f; } var ci = new CombineInstance { mesh = MeshFactory.MakeBillboardQuad(starSize), transform = MatrixHelper.BillboardMatrix(star.Position * StarsDistance) }; ci.mesh.colors = new Color[] { star.Color, star.Color, star.Color, star.Color }; starsCIs.Add(ci); } } var mesh = new Mesh(); mesh.CombineMeshes(starsCIs.ToArray()); mesh.name = string.Format("StarfieldMesh_({0})", Random.Range(float.MinValue, float.MaxValue)); mesh.bounds = new Bounds(Vector3.zero, new Vector3(1e8f, 1e8f, 1e8f)); mesh.hideFlags = HideFlags.DontSave; #region Cleanup foreach (var ci in starsCIs) { Helper.Destroy(ci.mesh); } starsCIs.Clear(); GC.Collect(); #endregion return(mesh); }
override public void Draw(Rect input, out Vector2[] output) { output = new Vector2[1]; if (!target.target.compiler || !target.target.compiler.material) { return; } for (int i = 0; i < output.Length; i++) { output[i] = Vector2.zero; } LAST_GROUP_R = new Rect(input.x, input.y, input.width, target.MENU_CURRENT_HEIGHT()); GUI.BeginGroup(LAST_GROUP_R); var r = new Rect(0, 0, BOTTOM_W * 1.333333f, 0); var og = GUI.enabled; // r.y += 10; GUI.enabled = target.DRAW_TOGGLE(r, "ZDepth Colorize", "USE_lerped_post", true, out tV); r.y += 31; target.DRAW_TOGGLE(r, "Use Deep Z Depth", "lerped_post_USE_depthZ", GUI.enabled, out tV); r.y += 31; r = target.DRAW_SLIDER(r, "Offset", "lerped_post_offset", -80, 80, GUI.enabled); r.y += r.height; r = target.DRAW_SLIDER(r, "Fallof", "lerped_post_offset_falloff", 0, 80, GUI.enabled); r.y += r.height; target.DRAW_TOGGLE(r, "Debug Offset", "lerped_post_Debug", GUI.enabled, out tV); r.y += 31; var oe = GUI.enabled; var c1 = target.DRAW_TOGGLE(r, "Color A", "USE_lerped_post_Color_1", oe, out tV) && oe; r.y += 31; GUI.enabled = c1; r.height = FastWaterModel20ControllerEditor.H; target.pop_zcolorize1.DrawPop(null, r); r.y += r.height; r = target.DRAW_COLOR(r, null, "lerped_post_color1", GUI.enabled, out tV, false); r.y += r.height; var c2 = target.DRAW_TOGGLE(r, "Color B", "USE_lerped_post_Color_2", oe, out tV) && oe; r.y += 31; GUI.enabled = c2; r.height = FastWaterModel20ControllerEditor.H; target.pop_zcolorize2.DrawPop(null, r); r.y += r.height; r = target.DRAW_COLOR(r, null, "lerped_post_color2", GUI.enabled, out tV, false); r.y += r.height; GUI.enabled = true; r.y += FastWaterModel20ControllerEditor.H; var ent = target.DRAW_TOGGLE(r, "Texture Colorize", "POST_TEXTURE_TINT", true, out tV); r.y += 31; GUI.enabled = ent; /* var foam = false; * if (target.MODE_ULTRA_FAST)foam = target.DRAW_TOGGLE(r, "Use Foam Texture", "POST_FOAM_TEXTURE", GUI.enabled, out tV) && GUI.enabled; r.y += 31; * var own = target.DRAW_TOGGLE(r, "Use Own Texture", "POST_OWN_TEXTURE", !foam && GUI.enabled, out tV) && !foam && GUI.enabled; r.y += 31; * GUI.enabled = ent; * if (foam) { r = target.DRAW_BG_TEXTURE(r, null, "_ShoreWavesGrad", foam, out tV, null); r.y += r.height; } * else if (own) { r = target.DRAW_BG_TEXTURE(r, null, "_MM_Texture", own, out tV, null); r.y += r.height; } * else { r = DRAW_GRAPHIC(r, 40, target.target.compiler.GetTexture(FIELDS._MainTex) as Texture2D, GUI.enabled, null); r.y += r.height; }*/ string[] texture = new[] { "_MainTex", "_UF_NMASK_Texture", "_ShoreWavesGrad", "_MM_Texture" }; POP_CLASS texture_SWITCHER = target.pop_postTExtureSwitcher; POP_CLASS pop_channel = target.pop_postTextureChannel; bool enable = GUI.enabled; ////////////////////////////// r = target.DrawTextureWIthChannelAndSwitcher(r, GUI.enabled, texture, texture_SWITCHER, pop_channel); /*r.height = FastWaterModel20ControllerEditor.H; * target.pop_mmchannel.DrawPop(null, r); r.y += r.height;*/ r = target.DRAW_VECTOR(r, "Tile X/Y", "_MM_Tile", 0, 10000, GUI.enabled, div: 100); r.y += r.height; r = target.DRAW_VECTOR(r, "Offset X/Y", "_MM_offset", 0, 10000, GUI.enabled, div: 100); r.y += r.height; r.height = FastWaterModel20ControllerEditor.H; target.pop_mmcolorize.DrawPop(null, r); r.y += r.height; if (target.pop_mmcolorize.VALUE == 2) { r = target.DRAW_SLIDER(r, "Multy Offset", "_MM_MultyOffset", 0, 1, GUI.enabled); r.y += r.height; } r = target.DRAW_COLOR(r, "Color", "_MM_Color", GUI.enabled, out tV, false); r.y += r.height; GUI.enabled = true; /* GUI.enabled = true; * var use_sg = GUI.enabled = target.DRAW_TOGGLE(r, "Surface Gradient", "USE_SURFACE_GRADS", GUI.enabled, out tV); r.y += 31; * r = target.DRAW_SLIDER(r, "Offset Top", "_WaveGradTopOffset", 0, 100, GUI.enabled); r.y += r.height; * target.DRAW_TOGGLE(r, "Debug Gradient", "DEBUG_TOP_GRAD", use_sg, out tV); r.y += 31; * r = target.DRAW_COLOR(r, null, "_WaveGrad0", use_sg, out tV, false); r.y += r.height; * r = target.DRAW_COLOR(r, null, "_WaveGrad1", use_sg, out tV, false); r.y += r.height; * r = target.DRAW_COLOR(r, null, "_WaveGrad2", use_sg, out tV, false); r.y += r.height; * r = target.DRAW_SLIDER(r, "Offset Mid", "_WaveGradMidOffset", 0, 1, GUI.enabled); r.y += r.height; * */ GUI.enabled = true; r.y += 10; r.x += r.width + 14; r.y = 0; GUI.enabled = og; GUI.enabled = target.DRAW_TOGGLE(r, "images_postrize", "POSTRIZE", true, out tV); r.y += 31; r = target.DRAW_SLIDER(r, "Posterize", "POSTRIZE_Colors", 1, 24, GUI.enabled); r.y += r.height; GUI.enabled = og; r.y += FastWaterModel20ControllerEditor.H; GUI.enabled = target.DRAW_TOGGLE(r, "Convert Colors", "USE_OUTPUT_GRADIENT", true, out tV); r.y += 31; target.DRAW_TOGGLE(r, "images_cc", null, GUI.enabled, out tV); r.y += 31; r.height = FastWaterModel20ControllerEditor.H; //EditorGUI.HelpBox( r, "Utils (RGB:y>0.5)", MessageType.None ); r.y += r.height; r = target.DRAW_BG_TEXTURE(r, "Gradient Texture", "_GradTexture", GUI.enabled, out tV, null); r.y += r.height; // r = DRAW_GRAPHIC( r, 40, target.target.material.GetTexture( FIELDS._Utility ) as Texture2D, GUI.enabled, new Color( 1, 1, 1, 1 ), YUP: 0.5f ); r.y += r.height; r.height = FastWaterModel20ControllerEditor.H; target.pop_gradientoutput.DrawPop(null, r); r.y += r.height; EditorGUI.HelpBox(r, "Blend Mode", MessageType.None); r.y += r.height; target.pop_outputblend.DrawPop(null, r); r.y += r.height; r = target.DRAW_SLIDER(r, "Blend", "_OutGradBlend", 0, 1, GUI.enabled); r.y += r.height; if (target.pop_outputblend.VALUE != 2) { if (target.__pop_depth != null && target.__pop_depth.VALUE == 0) { r.height = FastWaterModel20ControllerEditor.H * 3; EditorGUI.HelpBox(r, "Request ZDepth", MessageType.Error); r.y += r.height; } r = target.DRAW_SLIDER(r, "ZDepth Affect", "_OutGradZ", 1, 100, GUI.enabled); r.y += r.height; } if (target.pop_outputblend.VALUE != 0) { var fhl = target.DRAW_TOGGLE(r, "Fix Highlights", "FIX_HL", GUI.enabled, out tV) & GUI.enabled; r.y += 31; if (fhl) { r = target.DRAW_SLIDER(r, "Clamp Value", "_FixHLClamp", 0.1f, 1, fhl); r.y += r.height; } } /*GUI.enabled = target.DRAW_TOGGLE(r, "Additional Shadows", "USE_OUTPUT_SHADOWS", GUI.enabled, out tV); r.y += 31; * if (GUI.enabled) r = target.DRAW_SLIDER(r, "Amount", "_OutShadowsAmount", 0, 2, GUI.enabled); r.y += r.height;*/ GUI.enabled = og; r.y += FastWaterModel20ControllerEditor.H; GUI.enabled = target.DRAW_TOGGLE(r, "images_rim", "RIM", true, out tV); r.y += 31; r = target.DRAW_BG_TEXTURE(r, "Gradient", "_RimGradient", GUI.enabled, out tV, null); r.y += r.height; r = target.DRAW_SLIDER_WITHTOGGLE(r, "Blend", "_RIM_BLEND", 0, 1, GUI.enabled, "USE_RIM_BLEND"); r.y += r.height; r.height = FastWaterModel20ControllerEditor.H * 2; if (target.target.compiler.IsKeywordEnabled("SKIP_FRESNEL_CALCULATION")) { EditorGUI.HelpBox(r, "Fresnel Disabled", MessageType.None); } else { EditorGUI.HelpBox(r, "Using Fresnel Channel", MessageType.None); } r.y += r.height; r = target.DRAW_SLIDER(r, "Rim Blend", "RIM_Plus", 0, 1, GUI.enabled, div: 100); r.y += r.height; r = target.DRAW_SLIDER(r, "Rim Pow", "RIM_Minus", 0, 256, GUI.enabled); r.y += r.height; // target.DRAW_TOGGLE(r, "Inverse", "RIM_INVERSE", GUI.enabled, out tV); r.y += 31; target.DRAW_TOGGLE(r, "Shore Affect", "RIM_SCHORE_SKIP", GUI.enabled, out tV); r.y += 31; target.DRAW_TOGGLE(r, "Rim Debug", "RIM_DEBUG", GUI.enabled, out tV); r.y += 31; GUI.enabled = true; r.y += 10; r.x += r.width + 14; r.y = 0; GUI.enabled = target.target.compiler.IsKeywordEnabled("USE_SHADOWS") && target.IS_OPAQUE; target.DRAW_TOGGLE(r, "Shadows", null, GUI.enabled, out tV); r.y += 31; r = target.DRAW_SLIDER(r, "Shadows Amount", "_ShadorAmount", 0, 1, GUI.enabled); r.y += r.height; GUI.enabled = true; r.y += FastWaterModel20ControllerEditor.H; r.height = FastWaterModel20ControllerEditor.H * 3; EditorGUI.HelpBox(r, "Is case, if you don't use fullscreen effects, you may apply LUT gradient here", MessageType.None); r.y += r.height; GUI.enabled = target.DRAW_TOGGLE(r, "Use LUT's", "USE_LUT", GUI.enabled, out tV); r.y += 31; r = target.DRAW_BG_TEXTURE(r, null, "_Lut2D", GUI.enabled, out tV, null); r.y += r.height; if (GUI.enabled) { var t = target.target.compiler.GetTexture("_Lut2D"); if (!t) { t = ASSIGN_LUT(); if (t) { target.target.Undo(); target.target.compiler.SetTexture("_Lut2D", t); target.target.SetDirty(); } } if (t) { var tp = new Vector4(1f / t.width, 1f / t.height, t.height - 1f, 0); if (tp != target.target.compiler.GetVector("_Lut2D_params")) { target.target.Undo(); target.target.compiler.SetVector("_Lut2D_params", tp); target.target.SetDirty(); } } } r = target.DRAW_SLIDER(r, "Amount", "_LutAmount", 0, 1, GUI.enabled); r.y += r.height; target.DRAW_TOGGLE(r, "HQ Mode", "LUT_HQ_MODE", GUI.enabled, out tV); r.y += 31; target.DRAW_TOGGLE(r, "Fix Overexposure", "FIX_OVEREXPO", GUI.enabled, out tV); r.y += 31; r.height = FastWaterModel20ControllerEditor.H * 3; EditorGUI.HelpBox(r, "Enable Fix if there're wrong colors near the overexposured pixels", MessageType.None); GUI.enabled = og; LAST_GROUP_R = Rect.zero; GUI.EndGroup(); }
public void GetData(int index, out float positionX, out float positionY, out float positionZ, Vector4 color) { var modelInfo = _ModelInfoList[index]; positionX = modelInfo.position.X; positionY = modelInfo.position.Y; positionZ = modelInfo.position.Z; color = modelInfo.color; }
/// <summary> /// Sets the packed vector from a Vector4. /// </summary> /// <param name="vector">Vector containing the components.</param> void IPackedVector.PackFromVector4(Vector4 vector) { _packedValue = (UInt16)((((int)(vector.X * 31.0f) & 0x1F) << 11) | (((int)(vector.Y * 63.0f) & 0x3F) << 5) | ((int)(vector.Z * 31.0f) & 0x1F)); }
public void FitViewports() { //TODO: this doesn't work right in every circumstance foreach (GLViewport v in _viewports) { Vector4 p = v.Percentages; GLViewport x = null, y = null, z = null, w = null; Vector4 diff = new Vector4(float.MaxValue); foreach (GLViewport v2 in _viewports) { if (v2 == v) { continue; } float diff2 = Math.Abs(p._x - v2.Percentages._x); if (diff2 <= diff._x) { x = v2; diff._x = diff2; } diff2 = Math.Abs(p._y - v2.Percentages._y); if (diff2 <= diff._y) { y = v2; diff._y = diff2; } diff2 = Math.Abs(p._z - v2.Percentages._z); if (diff2 <= diff._z) { z = v2; diff._z = diff2; } diff2 = Math.Abs(p._w - v2.Percentages._w); if (diff2 <= diff._w) { w = v2; diff._w = diff2; } } Vector4 average = new Vector4(0.0f, 0.0f, 1.0f, 1.0f); if (diff._x > 0.0f && x != null) { average._x = (v.Percentages._x + x.Percentages._x) / 2.0f; x.SetXPercentage(average._x); } if (diff._y > 0.0f && y != null) { average._y = (v.Percentages._y + y.Percentages._y) / 2.0f; y.SetYPercentage(average._y); } if (diff._z > 0.0f && z != null) { average._z = (v.Percentages._z + z.Percentages._z) / 2.0f; z.SetZPercentage(average._z); } if (diff._w > 0.0f && w != null) { average._w = (v.Percentages._w + w.Percentages._w) / 2.0f; w.SetWPercentage(average._w); } v.SetPercentages(average); } }
/// <summary> /// Calculates the dot product of the specified vector and plane. /// </summary> /// <param name="left">The source plane.</param> /// <param name="right">The source vector.</param> /// <param name="result">When the method completes, contains the dot product of the specified plane and vector.</param> public static void Dot(ref Plane left, ref Vector4 right, out float result) { result = (left.Normal.X * right.X) + (left.Normal.Y * right.Y) + (left.Normal.Z * right.Z) + (left.D * right.W); }
public static Mesh Combine (MeshInstance[] combines) { int vertexCount = 0; int triangleCount = 0; foreach( MeshInstance combine in combines ) { if (combine.mesh) { vertexCount += combine.mesh.vertexCount; } } // Precomputed how many triangles we need instead foreach( MeshInstance combine in combines ) { if (combine.mesh) { triangleCount += combine.mesh.GetTriangles(combine.subMeshIndex).Length; } } Vector3[] vertices = new Vector3[vertexCount] ; Vector3[] normals = new Vector3[vertexCount] ; Vector4[] tangents = new Vector4[vertexCount] ; Vector2[] uv = new Vector2[vertexCount]; Vector2[] uv1 = new Vector2[vertexCount]; int offset; offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) Copy(combine.mesh.vertexCount, combine.mesh.vertices, vertices, ref offset, combine.transform); } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) { Matrix4x4 invTranspose = combine.transform; invTranspose = invTranspose.inverse.transpose; CopyNormal(combine.mesh.vertexCount, combine.mesh.normals, normals, ref offset, invTranspose); } } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) { Matrix4x4 invTranspose = combine.transform; invTranspose = invTranspose.inverse.transpose; CopyTangents(combine.mesh.vertexCount, combine.mesh.tangents, tangents, ref offset, invTranspose); } } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) Copy(combine.mesh.vertexCount, combine.mesh.uv, uv, ref offset); } offset=0; foreach( MeshInstance combine in combines ) { if (combine.mesh) Copy(combine.mesh.vertexCount, combine.mesh.uv1, uv1, ref offset); } int triangleOffset=0; int vertexOffset=0; int j=0; Mesh mesh = new Mesh(); mesh.vertices = vertices; mesh.normals = normals; mesh.uv = uv; mesh.uv1 = uv1; mesh.tangents = tangents; //Setting SubMeshes mesh.subMeshCount = combines.Length; foreach( MeshInstance combine in combines ) { int[] inputtriangles = combine.mesh.GetTriangles(combine.subMeshIndex); int[] trianglesx = new int[inputtriangles.Length]; for (int i=0;i<inputtriangles.Length;i++) { //triangles[i+triangleOffset] = inputtriangles[i] + vertexOffset; trianglesx[i] = inputtriangles[i] + vertexOffset; } triangleOffset += inputtriangles.Length; mesh.SetTriangles(trianglesx,j++); vertexOffset += combine.mesh.vertexCount; } mesh.name = "Combined Mesh"; return mesh; }
private void DrawOnTexture(RenderTexture rt, Material mat, int pass, List <Vector4> worldPoints, GStylizedTerrain t) { Vector4 worldOffset = new Vector4(0, HeightOffset, 0, 0); List <Vector4> normalizedPoints = new List <Vector4>(); for (int i = 0; i < worldPoints.Count; ++i) { Vector3 v = t.WorldPointToNormalized(worldPoints[i] + worldOffset); normalizedPoints.Add(new Vector4(Mathf.Clamp01(v.x), Mathf.Clamp01(v.y), Mathf.Clamp01(v.z), worldPoints[i].w)); } RenderTexture.active = rt; GL.PushMatrix(); GL.LoadOrtho(); GL.Begin(GL.TRIANGLES); int trisCount = worldPoints.Count / 3; GCommon.SetMaterialKeywordActive(mat, "FALLOFF", true); mat.SetPass(pass); for (int i = 0; i < trisCount; ++i) { Vector4 v0 = worldPoints[i * 3 + 0]; Vector4 v1 = worldPoints[i * 3 + 1]; Vector4 v2 = worldPoints[i * 3 + 2]; if (v0.w == 0 || v1.w == 0 || v2.w == 0) { Vector4 vn0 = normalizedPoints[i * 3 + 0]; Vector4 vn1 = normalizedPoints[i * 3 + 1]; Vector4 vn2 = normalizedPoints[i * 3 + 2]; GL.MultiTexCoord3(0, vn0.x, vn0.z, vn0.y); GL.MultiTexCoord3(1, v0.x, v0.z, v0.y); GL.Color(new Color(vn0.w, vn0.w, vn0.w, vn0.w)); GL.Vertex3(vn0.x, vn0.z, vn0.y); GL.MultiTexCoord3(0, vn1.x, vn1.z, vn1.y); GL.MultiTexCoord3(1, v1.x, v1.z, v1.y); GL.Color(new Color(vn1.w, vn1.w, vn1.w, vn1.w)); GL.Vertex3(vn1.x, vn1.z, vn1.y); GL.MultiTexCoord3(0, vn2.x, vn2.z, vn2.y); GL.MultiTexCoord3(1, v2.x, v2.z, v2.y); GL.Color(new Color(vn2.w, vn2.w, vn2.w, vn2.w)); GL.Vertex3(vn2.x, vn2.z, vn2.y); } } GL.End(); GL.Begin(GL.TRIANGLES); GCommon.SetMaterialKeywordActive(mat, "FALLOFF", false); mat.SetPass(pass); for (int i = 0; i < trisCount; ++i) { Vector4 v0 = worldPoints[i * 3 + 0]; Vector4 v1 = worldPoints[i * 3 + 1]; Vector4 v2 = worldPoints[i * 3 + 2]; if (v0.w != 0 && v1.w != 0 && v2.w != 0) { Vector4 vn0 = normalizedPoints[i * 3 + 0]; Vector4 vn1 = normalizedPoints[i * 3 + 1]; Vector4 vn2 = normalizedPoints[i * 3 + 2]; GL.MultiTexCoord3(0, vn0.x, vn0.z, vn0.y); GL.MultiTexCoord3(1, v0.x, v0.z, v0.y); GL.Color(new Color(vn0.w, vn0.w, vn0.w, vn0.w)); GL.Vertex3(vn0.x, vn0.z, vn0.y); GL.MultiTexCoord3(0, vn1.x, vn1.z, vn1.y); GL.MultiTexCoord3(1, v1.x, v1.z, v1.y); GL.Color(new Color(vn1.w, vn1.w, vn1.w, vn1.w)); GL.Vertex3(vn1.x, vn1.z, vn1.y); GL.MultiTexCoord3(0, vn2.x, vn2.z, vn2.y); GL.MultiTexCoord3(1, v2.x, v2.z, v2.y); GL.Color(new Color(vn2.w, vn2.w, vn2.w, vn2.w)); GL.Vertex3(vn2.x, vn2.z, vn2.y); } } GL.End(); GL.PopMatrix(); RenderTexture.active = null; }
internal void DrawSpriteGlyphDF(Texture2D texture, Vector4 dest, Vector4 source, Color color, float font_scale) { if (!m_DrawString_InProgress) Logging.Fatal("BeginDrawString() must be called before DrawSpriteGlyph()"); Vector4 uv = new Vector4( (float)source.X / texture.Width, (float)source.Y / texture.Height, (float)(source.X + source.Z) / texture.Width, (float)(source.Y + source.W) / texture.Height); float smoothing = 0.4f * Math.Pow(0.333f, font_scale * 2f) + 0.05f; Vector4 extra = new Vector4(0, 0, smoothing, 2); VertexPositionTextureHueExtra[] v = new VertexPositionTextureHueExtra[4] { new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y, m_DrawString_Depth), new Vector2(uv.X, uv.Y), color, extra), // top left new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y, m_DrawString_Depth), new Vector2(uv.Z, uv.Y), color, extra), // top right new VertexPositionTextureHueExtra(new Vector3(dest.X, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.X, uv.W), color, extra), // bottom left new VertexPositionTextureHueExtra(new Vector3(dest.X + dest.Z, dest.Y + dest.W, m_DrawString_Depth), new Vector2(uv.Z, uv.W), color, extra) // bottom right }; for (int i = 0; i < 4; i++) m_DrawString_VertexList.Add(v[i]); }