public void BindRayTracedReflectionData(CommandBuffer cmd, HDCamera hdCamera, HDRaytracingEnvironment rtEnvironment, RayTracingShader reflectionShader, ScreenSpaceReflection settings, LightCluster lightClusterSettings)
        {
            // Grab the acceleration structures and the light cluster to use
            RayTracingAccelerationStructure accelerationStructure = m_RayTracingManager.RequestAccelerationStructure(rtEnvironment.reflLayerMask);
            HDRaytracingLightCluster        lightCluster          = m_RayTracingManager.RequestLightCluster(rtEnvironment.reflLayerMask);

            // Define the shader pass to use for the reflection pass
            cmd.SetRayTracingShaderPass(reflectionShader, "IndirectDXR");

            // Set the acceleration structure for the pass
            cmd.SetRayTracingAccelerationStructure(reflectionShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure);

            // Inject the ray-tracing sampling data
            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._OwenScrambledTexture, m_Asset.renderPipelineResources.textures.owenScrambledTex);
            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._ScramblingTexture, m_Asset.renderPipelineResources.textures.scramblingTex);

            // Global reflection parameters
            cmd.SetRayTracingFloatParams(reflectionShader, HDShaderIDs._RaytracingIntensityClamp, settings.clampValue.value);
            cmd.SetRayTracingFloatParams(reflectionShader, HDShaderIDs._RaytracingReflectionMinSmoothness, settings.minSmoothness.value);
            cmd.SetRayTracingIntParams(reflectionShader, HDShaderIDs._RaytracingReflectSky, settings.reflectSky.value ? 1 : 0);

            // Inject the ray generation data
            cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtEnvironment.rayBias);
            cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, settings.rayLength.value);
            cmd.SetRayTracingIntParams(reflectionShader, HDShaderIDs._RaytracingNumSamples, settings.numSamples.value);
            int frameIndex = hdCamera.IsTAAEnabled() ? hdCamera.taaFrameIndex : (int)m_FrameCount % 8;

            cmd.SetRayTracingIntParam(reflectionShader, HDShaderIDs._RaytracingFrameIndex, frameIndex);

            // Set the data for the ray generation
            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._SsrLightingTextureRW, m_ReflIntermediateTexture0);
            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._SsrHitPointTexture, m_ReflIntermediateTexture1);
            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());

            // Set ray count tex
            cmd.SetRayTracingIntParam(reflectionShader, HDShaderIDs._RayCountEnabled, m_RayTracingManager.rayCountManager.RayCountIsEnabled());
            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._RayCountTexture, m_RayTracingManager.rayCountManager.rayCountTexture);


            // Compute the pixel spread value
            float pixelSpreadAngle = Mathf.Atan(2.0f * Mathf.Tan(hdCamera.camera.fieldOfView * Mathf.PI / 360.0f) / Mathf.Min(hdCamera.actualWidth, hdCamera.actualHeight));

            cmd.SetRayTracingFloatParam(reflectionShader, HDShaderIDs._RaytracingPixelSpreadAngle, pixelSpreadAngle);

            // LightLoop data
            cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster());
            cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, lightCluster.GetLightDatas());
            cmd.SetGlobalVector(HDShaderIDs._MinClusterPos, lightCluster.GetMinClusterPos());
            cmd.SetGlobalVector(HDShaderIDs._MaxClusterPos, lightCluster.GetMaxClusterPos());
            cmd.SetGlobalInt(HDShaderIDs._LightPerCellCount, lightClusterSettings.maxNumLightsPercell.value);
            cmd.SetGlobalInt(HDShaderIDs._PunctualLightCountRT, lightCluster.GetPunctualLightCount());
            cmd.SetGlobalInt(HDShaderIDs._AreaLightCountRT, lightCluster.GetAreaLightCount());

            // Note: Just in case, we rebind the directional light data (in case they were not)
            cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData);
            cmd.SetGlobalInt(HDShaderIDs._DirectionalLightCount, m_lightList.directionalLights.Count);

            // Evaluate the clear coat mask texture based on the lit shader mode
            RenderTargetIdentifier clearCoatMaskTexture = hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred ? m_GbufferManager.GetBuffersRTI()[2] : TextureXR.GetBlackTexture();

            cmd.SetRayTracingTextureParam(reflectionShader, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMaskTexture);
        }
 /// <summary>
 /// Get the horizontal FOV from the stereo camera
 /// </summary>
 public static float GetHorizontalFieldOfViewRadians(this Camera camera)
 {
     return(2f * Mathf.Atan(Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad * 0.5f) * camera.aspect));
 }
Exemple #3
0
    public virtual IEnumerator Start()
    {
        findS3dCamera();
        checkpoints = new Vector2[5];
        objectCopyR = UnityEngine.Object.Instantiate(gameObject, transform.position, transform.rotation);
        UnityEngine.Object.Destroy((s3dGuiTexture)objectCopyR.GetComponent(typeof(s3dGuiTexture)));
        objectCopyR.name  = gameObject.name + "_R";
        gameObject.name   = gameObject.name + "_L";
        gameObject.layer  = camera3D.leftOnlyLayer;
        objectCopyR.layer = camera3D.rightOnlyLayer;
        obPosition        = gameObject.transform.position;

        // if using stereo shader + side-by-side + not squeezed, double width of guiTexture
        if ((camera3D.useStereoShader && (camera3D.format3D == (mode3D)0)) && !camera3D.sideBySideSqueezed)
        {
            xWidth = GetComponent <GUITexture>().pixelInset.width * 2;

            {
                float _33 = xWidth;
                Rect  _34 = gameObject.GetComponent <GUITexture>().pixelInset;
                _34.width = _33;
                gameObject.GetComponent <GUITexture>().pixelInset = _34;
            }

            {
                float _35 = xWidth;
                Rect  _36 = objectCopyR.GetComponent <GUITexture>().pixelInset;
                _36.width = _35;
                objectCopyR.GetComponent <GUITexture>().pixelInset = _36;
            }
            xInset = gameObject.GetComponent <GUITexture>().pixelInset.width / -2;

            {
                float _37 = xInset;
                Rect  _38 = gameObject.GetComponent <GUITexture>().pixelInset;
                _38.x = _37;
                gameObject.GetComponent <GUITexture>().pixelInset = _38;
            }

            {
                float _39 = xInset;
                Rect  _40 = objectCopyR.GetComponent <GUITexture>().pixelInset;
                _40.x = _39;
                objectCopyR.GetComponent <GUITexture>().pixelInset = _40;
            }
        }
        else
        {
            // if not using stereo shader + squeezed, halve width of guiTexture
            if (!camera3D.useStereoShader && camera3D.sideBySideSqueezed)
            {
                xWidth = gameObject.GetComponent <GUITexture>().pixelInset.width * 0.5f;

                {
                    float _41 = xWidth;
                    Rect  _42 = gameObject.GetComponent <GUITexture>().pixelInset;
                    _42.width = _41;
                    gameObject.GetComponent <GUITexture>().pixelInset = _42;
                }

                {
                    float _43 = xWidth;
                    Rect  _44 = objectCopyR.GetComponent <GUITexture>().pixelInset;
                    _44.width = _43;
                    objectCopyR.GetComponent <GUITexture>().pixelInset = _44;
                }
                xInset = gameObject.GetComponent <GUITexture>().pixelInset.width / -2;

                {
                    float _45 = xInset;
                    Rect  _46 = gameObject.GetComponent <GUITexture>().pixelInset;
                    _46.x = _45;
                    gameObject.GetComponent <GUITexture>().pixelInset = _46;
                }

                {
                    float _47 = xInset;
                    Rect  _48 = objectCopyR.GetComponent <GUITexture>().pixelInset;
                    _48.x = _47;
                    objectCopyR.GetComponent <GUITexture>().pixelInset = _48;
                }
            }
        }
        // find corner offset
        corner = new Vector2((gameObject.GetComponent <GUITexture>().pixelInset.width / 2) / Screen.width, (gameObject.GetComponent <GUITexture>().pixelInset.height / 2) / Screen.height);
        toggleVisible(beginVisible);
        float horizontalFOV = (2 * Mathf.Atan(Mathf.Tan((camera3D.GetComponent <Camera>().fieldOfView *Mathf.Deg2Rad) / 2) * camera3D.GetComponent <Camera>().aspect)) * Mathf.Rad2Deg;

        unitWidth   = Mathf.Tan((horizontalFOV / 2) * Mathf.Deg2Rad); // need unit width to calculate cursor depth when there's a HIT (horizontal image transform)
        screenWidth = (unitWidth * camera3D.zeroPrlxDist) * 2;
        setScreenParallax();
        if (timeToDisplay != 0f)
        {
            yield return(new WaitForSeconds(timeToDisplay));

            toggleVisible(false);
        }
        s3dCursor = (s3dGuiCursor)gameObject.GetComponent(typeof(s3dGuiCursor));
        if (s3dCursor)
        {
            s3dCursor.initialize();
        }
    }
Exemple #4
0
        /// <summary>
        /// Raises the web cam texture to mat helper initialized event.
        /// </summary>
        public void OnWebCamTextureToMatHelperInitialized()
        {
            Debug.Log("OnWebCamTextureToMatHelperInitialized");

            Mat webCamTextureMat = webCamTextureToMatHelper.GetMat();


            #if NETFX_CORE && !DISABLE_HOLOLENSCAMSTREAM_API
            // HololensCameraStream always returns image data in BGRA format.
            texture = new Texture2D(webCamTextureMat.cols(), webCamTextureMat.rows(), TextureFormat.BGRA32, false);
            #else
            texture = new Texture2D(webCamTextureMat.cols(), webCamTextureMat.rows(), TextureFormat.RGBA32, false);
            #endif

            texture.wrapMode = TextureWrapMode.Clamp;

            Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);


            processingAreaRect = new OpenCVForUnity.Rect((int)(webCamTextureMat.cols() * (outsideClippingRatio.x - clippingOffset.x)), (int)(webCamTextureMat.rows() * (outsideClippingRatio.y + clippingOffset.y)),
                                                         (int)(webCamTextureMat.cols() * (1f - outsideClippingRatio.x * 2)), (int)(webCamTextureMat.rows() * (1f - outsideClippingRatio.y * 2)));
            processingAreaRect = processingAreaRect.intersect(new OpenCVForUnity.Rect(0, 0, webCamTextureMat.cols(), webCamTextureMat.rows()));


            dstMat            = new Mat(webCamTextureMat.rows(), webCamTextureMat.cols(), CvType.CV_8UC1);
            dstMatClippingROI = new Mat(dstMat, processingAreaRect);

            // fill all black.
            //Imgproc.rectangle (dstMat, new Point (0, 0), new Point (dstMat.width (), dstMat.height ()), new Scalar (0, 0, 0, 0), -1);


            grayMat = new Mat(dstMatClippingROI.rows(), dstMatClippingROI.cols(), CvType.CV_8UC1);
            lineMat = new Mat(dstMatClippingROI.rows(), dstMatClippingROI.cols(), CvType.CV_8UC1);
            maskMat = new Mat(dstMatClippingROI.rows(), dstMatClippingROI.cols(), CvType.CV_8UC1);

            //create a striped background.
            bgMat = new Mat(dstMatClippingROI.rows(), dstMatClippingROI.cols(), CvType.CV_8UC1, new Scalar(255));
            for (int i = 0; i < bgMat.rows() * 2.5f; i = i + 4)
            {
                Imgproc.line(bgMat, new Point(0, 0 + i), new Point(bgMat.cols(), -bgMat.cols() + i), new Scalar(0), 1);
            }

            grayPixels = new byte[grayMat.cols() * grayMat.rows() * grayMat.channels()];
            maskPixels = new byte[maskMat.cols() * maskMat.rows() * maskMat.channels()];


            quad_renderer = gameObject.GetComponent <Renderer> () as Renderer;
            quad_renderer.sharedMaterial.SetTexture("_MainTex", texture);
            quad_renderer.sharedMaterial.SetVector("_VignetteOffset", new Vector4(clippingOffset.x, clippingOffset.y));

            Matrix4x4 projectionMatrix;
            #if NETFX_CORE && !DISABLE_HOLOLENSCAMSTREAM_API
            projectionMatrix = webCamTextureToMatHelper.GetProjectionMatrix();
            quad_renderer.sharedMaterial.SetMatrix("_CameraProjectionMatrix", projectionMatrix);
            #else
            //This value is obtained from PhotoCapture's TryGetProjectionMatrix() method.I do not know whether this method is good.
            //Please see the discussion of this thread.Https://forums.hololens.com/discussion/782/live-stream-of-locatable-camera-webcam-in-unity
            projectionMatrix     = Matrix4x4.identity;
            projectionMatrix.m00 = 2.31029f;
            projectionMatrix.m01 = 0.00000f;
            projectionMatrix.m02 = 0.09614f;
            projectionMatrix.m03 = 0.00000f;
            projectionMatrix.m10 = 0.00000f;
            projectionMatrix.m11 = 4.10427f;
            projectionMatrix.m12 = -0.06231f;
            projectionMatrix.m13 = 0.00000f;
            projectionMatrix.m20 = 0.00000f;
            projectionMatrix.m21 = 0.00000f;
            projectionMatrix.m22 = -1.00000f;
            projectionMatrix.m23 = 0.00000f;
            projectionMatrix.m30 = 0.00000f;
            projectionMatrix.m31 = 0.00000f;
            projectionMatrix.m32 = -1.00000f;
            projectionMatrix.m33 = 0.00000f;
            quad_renderer.sharedMaterial.SetMatrix("_CameraProjectionMatrix", projectionMatrix);
            #endif

            quad_renderer.sharedMaterial.SetFloat("_VignetteScale", vignetteScale);


            float halfOfVerticalFov = Mathf.Atan(1.0f / projectionMatrix.m11);
            float aspectRatio       = (1.0f / Mathf.Tan(halfOfVerticalFov)) / projectionMatrix.m00;
            Debug.Log("halfOfVerticalFov " + halfOfVerticalFov);
            Debug.Log("aspectRatio " + aspectRatio);

            //
            //Imgproc.rectangle (dstMat, new Point (0, 0), new Point (webCamTextureMat.width (), webCamTextureMat.height ()), new Scalar (126, 126, 126, 255), -1);
            //
        }
Exemple #5
0
    /// <summary>
    /// Update Arm Shape
    /// target: Keypoint to modify
    /// Returns modified keypoint
    /// </summary>
    Vector3  ArmShape(int arm, Vector3 target, Vector3 shoulderPos)
    {
        float   rotTheta = 0f;
        Vector3 centerEllipse;
        //Transform target from world space to local EMOTE coordinates
        //	targetLocal = transform.InverseTransformPoint(target);
        //Translate to world

        //Vector3 targetLocal = target - _arms[arm].Shoulder.position;



        Vector3 targetLocal = target - shoulderPos;


        //  Debug.Log(targetLocal);
        //Rotate to emote
        targetLocal = new Vector3(targetLocal.y, -targetLocal.z, targetLocal.x);

        //hor
        float theta = Mathf.Atan(Abratio * targetLocal.y / -targetLocal.z);

        if (-targetLocal.z < 0)
        {
            theta += Mathf.PI;
        }
        if (theta < 0)
        {
            theta += 2 * Mathf.PI;
        }

        float a = -targetLocal.z / Mathf.Cos(theta);



        if (Hor == 0)
        {
            // WRONG! rotTheta = 0f;
            rotTheta = theta;
        }
        else if (Hor < 0f && 0 < theta && theta <= Mathf.PI)
        {
            rotTheta = Mathf.Min(theta - Hor * MaxdTheta, Mathf.PI);
        }
        else if (Hor < 0f && Mathf.PI < theta && theta <= 2 * Mathf.PI)
        {
            rotTheta = Mathf.Max(theta + Hor * MaxdTheta, Mathf.PI);
        }
        else if (Hor > 0f && 0 < theta && theta <= Mathf.PI)
        {
            rotTheta = Mathf.Max(theta - Hor * MaxdTheta, 0);
        }
        else if (Hor > 0f && Mathf.PI < theta && theta <= 2 * Mathf.PI)
        {
            rotTheta = Mathf.Min(theta + Hor * MaxdTheta, 2 * Mathf.PI);
        }


        float hdz = -(a * Mathf.Cos(rotTheta)) - targetLocal.z;
        float hdy = (a * Mathf.Sin(rotTheta) / Abratio) - targetLocal.y;



        //sag
        theta = Mathf.Atan(Abratio * targetLocal.x / -targetLocal.y);


        if (targetLocal.y < 0)
        {
            theta += Mathf.PI;
        }
        if (theta < 0)
        {
            theta += 2 * Mathf.PI;
        }



        a = targetLocal.y / Mathf.Cos(theta);

        if (Sag == 0)
        {
            // WRONG! rotTheta = 0f;
            rotTheta = theta;
        }
        else if (Sag < 0f && 0 < theta && theta <= Mathf.PI)
        {
            rotTheta = Mathf.Min(theta - Sag * MaxdTheta, Mathf.PI);
        }
        else if (Sag < 0f && Mathf.PI < theta && theta <= 2 * Mathf.PI)
        {
            rotTheta = Mathf.Max(theta + Sag * MaxdTheta, Mathf.PI);
        }
        else if (Sag > 0f && 0 < theta && theta <= Mathf.PI)
        {
            rotTheta = Mathf.Max(theta - Sag * MaxdTheta, 0);
        }
        else if (Sag > 0f && Mathf.PI < theta && theta <= 2 * Mathf.PI)
        {
            rotTheta = Mathf.Min(theta + Sag * MaxdTheta, 2 * Mathf.PI);
        }


        float sdx = -(a * Mathf.Sin(rotTheta) / Abratio) - targetLocal.x;
        float sdy = (a * Mathf.Cos(rotTheta)) - targetLocal.y;


        //ver
        theta = Mathf.Atan(-Abratio * targetLocal.z / -targetLocal.x);
        if (-targetLocal.x < 0)
        {
            theta += Mathf.PI;
        }
        if (theta < 0)
        {
            theta += 2 * Mathf.PI;
        }

        a = -targetLocal.x / Mathf.Cos(theta);


        if (Ver == 0)
        {
            // WRONG! rotTheta = 0f;
            rotTheta = theta;
        }
        else if (Ver < 0f && 0 < theta && theta <= Mathf.PI)
        {
            rotTheta = Mathf.Min(theta - Ver * MaxdTheta, Mathf.PI);
        }
        else if (Ver < 0f && Mathf.PI < theta && theta <= 2 * Mathf.PI)
        {
            rotTheta = Mathf.Max(theta + Ver * MaxdTheta, Mathf.PI);
        }
        else if (Ver > 0f && 0 < theta && theta <= Mathf.PI)
        {
            rotTheta = Mathf.Max(theta - Ver * MaxdTheta, 0);
        }
        else if (Ver > 0f && Mathf.PI < theta && theta <= 2 * Mathf.PI)
        {
            rotTheta = Mathf.Min(theta + Ver * MaxdTheta, 2 * Mathf.PI);
        }


        float vdx = -(a * Mathf.Cos(rotTheta)) - targetLocal.x;
        float vdz = -(a * Mathf.Sin(rotTheta) / Abratio) - targetLocal.z;

        if (Mathf.Abs(sdx) < 0.0001f)
        {
            sdx = 0f;
        }
        if (Mathf.Abs(sdy) < 0.0001f)
        {
            sdy = 0f;
        }
        if (Mathf.Abs(vdx) < 0.0001f)
        {
            vdx = 0f;
        }
        if (Mathf.Abs(vdz) < 0.0001f)
        {
            vdz = 0f;
        }
        if (Mathf.Abs(hdy) < 0.0001f)
        {
            hdy = 0f;
        }
        if (Mathf.Abs(hdz) < 0.0001f)
        {
            hdz = 0f;
        }


        //Update keypoint position

        if (arm == 1)
        {
            sdx = -sdx;
        }

        targetLocal.x += sdx + vdx;
        targetLocal.y += sdy + hdy;
        targetLocal.z += hdz + vdz;


        //Transform target from local EMOTE space to world coordinates

        //	target = transform.TransformPoint(targetLocal);

        //Convert back to unity coordinate system
        targetLocal = new Vector3(targetLocal.z, targetLocal.x, -targetLocal.y);


        //Translate back to world coordinate
        //target = targetLocal + _arms[arm].Shoulder.position;
        target = targetLocal + shoulderPos;

        return(target);
    }
Exemple #6
0
        public void Render(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle outputTexture, ScriptableRenderContext renderContext, CullingResults cull)
        {
            // First thing to check is: Do we have a valid ray-tracing environment?
            HDRaytracingEnvironment rtEnvironement = m_RaytracingManager.CurrentEnvironment();
            RaytracingShader        forwardShader  = m_PipelineAsset.renderPipelineResources.shaders.forwardRaytracing;
            Shader raytracingMask = m_PipelineAsset.renderPipelineResources.shaders.raytracingFlagMask;

            // Check the validity of the state before computing the effect
            bool invalidState = rtEnvironement == null || !rtEnvironement.raytracedObjects ||
                                forwardShader == null || raytracingMask == null ||
                                m_PipelineResources.textures.owenScrambledTex == null || m_PipelineResources.textures.scramblingTex == null;

            // If any resource or game-object is missing We stop right away
            if (invalidState)
            {
                return;
            }

            // Grab the acceleration structure and the list of HD lights for the target camera
            RaytracingAccelerationStructure accelerationStructure = m_RaytracingManager.RequestAccelerationStructure(rtEnvironement.raytracedLayerMask);
            HDRaytracingLightCluster        lightCluster          = m_RaytracingManager.RequestLightCluster(rtEnvironement.raytracedLayerMask);

            if (m_RaytracingFlagMaterial == null)
            {
                m_RaytracingFlagMaterial = CoreUtils.CreateEngineMaterial(raytracingMask);
            }

            // Before going into raytracing, we need to flag which pixels needs to be raytracing
            EvaluateRaytracingMask(cull, hdCamera, cmd, renderContext);

            // Define the shader pass to use for the reflection pass
            cmd.SetRaytracingShaderPass(forwardShader, "ForwardDXR");

            // Set the acceleration structure for the pass
            cmd.SetRaytracingAccelerationStructure(forwardShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure);

            // Inject the ray-tracing sampling data
            cmd.SetRaytracingTextureParam(forwardShader, m_RayGenShaderName, HDShaderIDs._OwenScrambledTexture, m_PipelineResources.textures.owenScrambledTex);
            cmd.SetRaytracingTextureParam(forwardShader, m_RayGenShaderName, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex);

            // Inject the ray generation data
            cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtEnvironement.rayBias);
            cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, rtEnvironement.raytracingRayLength);
            cmd.SetGlobalFloat(HDShaderIDs._RaytracingMaxRecursion, rtEnvironement.rayMaxDepth);

            // Set the data for the ray generation
            cmd.SetRaytracingTextureParam(forwardShader, m_RayGenShaderName, HDShaderIDs._RaytracingFlagMask, m_RaytracingFlagTarget);
            cmd.SetRaytracingTextureParam(forwardShader, m_RayGenShaderName, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
            cmd.SetRaytracingTextureParam(forwardShader, m_RayGenShaderName, HDShaderIDs._CameraColorTextureRW, outputTexture);

            // Compute the pixel spread value
            float pixelSpreadAngle = Mathf.Atan(2.0f * Mathf.Tan(hdCamera.camera.fieldOfView * Mathf.PI / 360.0f) / Mathf.Min(hdCamera.actualWidth, hdCamera.actualHeight));

            cmd.SetRaytracingFloatParam(forwardShader, HDShaderIDs._PixelSpreadAngle, pixelSpreadAngle);

            // Set the light cluster data if available
            {
                // LightLoop data
                cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster());
                cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, lightCluster.GetLightDatas());
                cmd.SetGlobalVector(HDShaderIDs._MinClusterPos, lightCluster.GetMinClusterPos());
                cmd.SetGlobalVector(HDShaderIDs._MaxClusterPos, lightCluster.GetMaxClusterPos());
                cmd.SetGlobalInt(HDShaderIDs._LightPerCellCount, rtEnvironement.maxNumLightsPercell);
                cmd.SetGlobalInt(HDShaderIDs._PunctualLightCountRT, lightCluster.GetPunctualLightCount());
                cmd.SetGlobalInt(HDShaderIDs._AreaLightCountRT, lightCluster.GetAreaLightCount());
            }

            // Set the data for the ray miss
            cmd.SetRaytracingTextureParam(forwardShader, m_MissShaderName, HDShaderIDs._SkyTexture, m_SkyManager.skyReflection);

            // Run the calculus
            cmd.DispatchRays(forwardShader, m_RayGenShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, 1);
        }
Exemple #7
0
        private void Run()
        {
            //set 3d face object points.
            objectPoints = new MatOfPoint3f(
                new Point3(-31, 72, 86), //l eye
                new Point3(31, 72, 86),  //r eye
                new Point3(0, 40, 114),  //nose
                new Point3(-20, 15, 90), //l mouse
                new Point3(20, 15, 90),  //r mouse
                new Point3(-69, 76, -2), //l ear
                new Point3(69, 76, -2)   //r ear
                );
            imagePoints = new MatOfPoint2f();
            rvec        = new Mat();
            tvec        = new Mat();
            rotMat      = new Mat(3, 3, CvType.CV_64FC1);

            faceLandmarkDetector = new FaceLandmarkDetector(shape_predictor_68_face_landmarks_dat_filepath);

            rgbMat = new Mat();

            capture = new VideoCapture();
            capture.open(dance_avi_filepath);

            if (capture.isOpened())
            {
                Debug.Log("capture.isOpened() true");
            }
            else
            {
                Debug.Log("capture.isOpened() false");
            }


            Debug.Log("CAP_PROP_FORMAT: " + capture.get(Videoio.CAP_PROP_FORMAT));
            Debug.Log("CV_CAP_PROP_PREVIEW_FORMAT: " + capture.get(Videoio.CV_CAP_PROP_PREVIEW_FORMAT));
            Debug.Log("CAP_PROP_POS_MSEC: " + capture.get(Videoio.CAP_PROP_POS_MSEC));
            Debug.Log("CAP_PROP_POS_FRAMES: " + capture.get(Videoio.CAP_PROP_POS_FRAMES));
            Debug.Log("CAP_PROP_POS_AVI_RATIO: " + capture.get(Videoio.CAP_PROP_POS_AVI_RATIO));
            Debug.Log("CAP_PROP_FRAME_COUNT: " + capture.get(Videoio.CAP_PROP_FRAME_COUNT));
            Debug.Log("CAP_PROP_FPS: " + capture.get(Videoio.CAP_PROP_FPS));
            Debug.Log("CAP_PROP_FRAME_WIDTH: " + capture.get(Videoio.CAP_PROP_FRAME_WIDTH));
            Debug.Log("CAP_PROP_FRAME_HEIGHT: " + capture.get(Videoio.CAP_PROP_FRAME_HEIGHT));

            capture.grab();
            capture.retrieve(rgbMat, 0);
            int frameWidth  = rgbMat.cols();
            int frameHeight = rgbMat.rows();

            colors  = new Color32[frameWidth * frameHeight];
            texture = new Texture2D(frameWidth, frameHeight, TextureFormat.RGBA32, false);
            gameObject.transform.localScale = new Vector3((float)frameWidth, (float)frameHeight, 1);
            capture.set(Videoio.CAP_PROP_POS_FRAMES, 0);

            gameObject.GetComponent <Renderer> ().material.mainTexture = texture;

            Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);


            float width  = (float)frameWidth;
            float height = (float)frameHeight;

            float imageSizeScale = 1.0f;
            float widthScale     = (float)Screen.width / width;
            float heightScale    = (float)Screen.height / height;

            if (widthScale < heightScale)
            {
                Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
                imageSizeScale = (float)Screen.height / (float)Screen.width;
            }
            else
            {
                Camera.main.orthographicSize = height / 2;
            }


            //set cameraparam
            int    max_d = (int)Mathf.Max(width, height);
            double fx    = max_d;
            double fy    = max_d;
            double cx    = width / 2.0f;
            double cy    = height / 2.0f;

            camMatrix = new Mat(3, 3, CvType.CV_64FC1);
            camMatrix.put(0, 0, fx);
            camMatrix.put(0, 1, 0);
            camMatrix.put(0, 2, cx);
            camMatrix.put(1, 0, 0);
            camMatrix.put(1, 1, fy);
            camMatrix.put(1, 2, cy);
            camMatrix.put(2, 0, 0);
            camMatrix.put(2, 1, 0);
            camMatrix.put(2, 2, 1.0f);
            Debug.Log("camMatrix " + camMatrix.dump());


            distCoeffs = new MatOfDouble(0, 0, 0, 0);
            Debug.Log("distCoeffs " + distCoeffs.dump());


            //calibration camera
            Size   imageSize      = new Size(width * imageSizeScale, height * imageSizeScale);
            double apertureWidth  = 0;
            double apertureHeight = 0;

            double[] fovx           = new double[1];
            double[] fovy           = new double[1];
            double[] focalLength    = new double[1];
            Point    principalPoint = new Point(0, 0);

            double[] aspectratio = new double[1];

            Calib3d.calibrationMatrixValues(camMatrix, imageSize, apertureWidth, apertureHeight, fovx, fovy, focalLength, principalPoint, aspectratio);

            Debug.Log("imageSize " + imageSize.ToString());
            Debug.Log("apertureWidth " + apertureWidth);
            Debug.Log("apertureHeight " + apertureHeight);
            Debug.Log("fovx " + fovx [0]);
            Debug.Log("fovy " + fovy [0]);
            Debug.Log("focalLength " + focalLength [0]);
            Debug.Log("principalPoint " + principalPoint.ToString());
            Debug.Log("aspectratio " + aspectratio [0]);


            //To convert the difference of the FOV value of the OpenCV and Unity.
            double fovXScale = (2.0 * Mathf.Atan((float)(imageSize.width / (2.0 * fx)))) / (Mathf.Atan2((float)cx, (float)fx) + Mathf.Atan2((float)(imageSize.width - cx), (float)fx));
            double fovYScale = (2.0 * Mathf.Atan((float)(imageSize.height / (2.0 * fy)))) / (Mathf.Atan2((float)cy, (float)fy) + Mathf.Atan2((float)(imageSize.height - cy), (float)fy));

            Debug.Log("fovXScale " + fovXScale);
            Debug.Log("fovYScale " + fovYScale);


            //Adjust Unity Camera FOV https://github.com/opencv/opencv/commit/8ed1945ccd52501f5ab22bdec6aa1f91f1e2cfd4
            if (widthScale < heightScale)
            {
                ARCamera.fieldOfView = (float)(fovx [0] * fovXScale);
            }
            else
            {
                ARCamera.fieldOfView = (float)(fovy [0] * fovYScale);
            }


            invertZM = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1, 1, -1));
            Debug.Log("invertZM " + invertZM.ToString());


            axes.SetActive(false);
            head.SetActive(false);
            rightEye.SetActive(false);
            leftEye.SetActive(false);
            mouth.SetActive(false);

            mouthParticleSystem = mouth.GetComponentsInChildren <ParticleSystem> (true);
        }
 // Expects a value between -1f and 1f and returns a value between -1f and 1f
 public static float ArctanDistribution(float x, float factor)
 {
     return(2f * Mathf.Atan(factor * x) / Mathf.PI);
 }
    //converts a vector to the local space, ignoring yaw.
    Vector3 convertToLocal(Vector3 global)
    {
        float gX, gY, gZ;

        float lX, lY, lZ, lZ2, pitch, roll;

        float zxAngle, zyAngle;

        gX = global.x;

        //Z and Y are switched, so we are swapping them here to make sense of them.
        gY = global.z;

        gZ = global.y;



        pitch = rate.xRotation;

        roll = rate.zRotation;

        if (flipXRots)
        {
            pitch *= -1;
        }
        if (flipZRots)
        {
            roll *= -1;
        }

        if (gX != 0)
        {
            zxAngle = Mathf.Rad2Deg * Mathf.Atan(Mathf.Abs(gX) / Mathf.Abs(gZ)) * (Mathf.Abs(gX) / gX) + 90 * ((Mathf.Abs(gZ) - gZ) / 2 * gZ) * -gX;
        }
        else
        {
            zxAngle = 0;
        }
        if (gY != 0)
        {
            zyAngle = Mathf.Rad2Deg * Mathf.Atan(Mathf.Abs(gY) / Mathf.Abs(gZ)) * (Mathf.Abs(gY) / gY) + 90 * ((Mathf.Abs(gZ) - gZ) / 2 * gZ) * -gY;
        }
        else
        {
            zyAngle = 0;
        }

        lX = Mathf.Sin(Mathf.Deg2Rad * (zxAngle - roll));


        lY = Mathf.Sin(Mathf.Deg2Rad * (zyAngle - pitch));

        lZ = Mathf.Cos(Mathf.Deg2Rad * (zxAngle - roll));

        lZ2 = Mathf.Cos(Mathf.Deg2Rad * (zyAngle - pitch));


        float magXZ = Mathf.Sqrt(lX * lX + lZ * lZ);

        lX /= magXZ;

        lZ /= magXZ;

        float magYZ = Mathf.Sqrt(lY * lY + lZ2 * lZ2);

        float equilizerMag = lZ2 / lZ;

        lY /= equilizerMag;

        lZ2 /= equilizerMag;

        Debug.Log("Pitch: " + pitch + " Roll: " + roll);

        Debug.Log("Vector is: <" + lX + "," + lY + "," + lZ + "> or <" + lX + "," + lY + "," + lZ2 + ">");


        //Swap the Y and Z back
        return(new Vector3(lX, lZ, lY));
    }
 private float roll()
 {
     return(Mathf.Atan(-Gx / Gz));
 }
Exemple #11
0
    // Use this for initialization

    // Update is called once per frame
    void Update()
    {
        pos  = Cam.WorldToScreenPoint(boneRef.transform.position);
        mPos = Input.mousePosition;
        boneRef.transform.localEulerAngles = new Vector3(0, 0, ((180.0f * Mathf.Atan((mPos.y - pos.y) / (mPos.x - pos.x))) / Mathf.PI));
    }
 private float pitch()
 {
     return(Mathf.Atan(Gy / (Mathf.Sqrt(Mathf.Pow(Gx, 2) + Mathf.Pow(Gz, 2)))));
 }
        private void BakeSettings()
        {
            EditorGUILayout.LabelField(NavMeshEditorWindow.s_Styles.m_AgentSizeHeader, EditorStyles.boldLabel, new GUILayoutOption[0]);
            Rect controlRect = EditorGUILayout.GetControlRect(false, 120f, new GUILayoutOption[0]);

            this.DrawAgentDiagram(controlRect, this.m_AgentRadius.floatValue, this.m_AgentHeight.floatValue, this.m_AgentClimb.floatValue, this.m_AgentSlope.floatValue);
            float num = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentRadiusContent, this.m_AgentRadius.floatValue, new GUILayoutOption[0]);

            if (num >= 0.001f && !Mathf.Approximately(num - this.m_AgentRadius.floatValue, 0f))
            {
                this.m_AgentRadius.floatValue = num;
                if (!this.m_ManualCellSize.boolValue)
                {
                    this.m_CellSize.floatValue = 2f * this.m_AgentRadius.floatValue / 6f;
                }
            }
            if (this.m_AgentRadius.floatValue < 0.05f && !this.m_ManualCellSize.boolValue)
            {
                EditorGUILayout.HelpBox("The agent radius you've set is really small, this can slow down the build.\nIf you intended to allow the agent to move close to the borders and walls, please adjust voxel size in advaced settings to ensure correct bake.", MessageType.Warning);
            }
            float num2 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentHeightContent, this.m_AgentHeight.floatValue, new GUILayoutOption[0]);

            if (num2 >= 0.001f && !Mathf.Approximately(num2 - this.m_AgentHeight.floatValue, 0f))
            {
                this.m_AgentHeight.floatValue = num2;
            }
            EditorGUILayout.Slider(this.m_AgentSlope, 0f, 60f, NavMeshEditorWindow.s_Styles.m_AgentSlopeContent, new GUILayoutOption[0]);
            if (this.m_AgentSlope.floatValue > 60f)
            {
                EditorGUILayout.HelpBox("The maximum slope should be set to less than " + 60f + " degrees to prevent NavMesh build artifacts on slopes. ", MessageType.Warning);
            }
            float num3 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentClimbContent, this.m_AgentClimb.floatValue, new GUILayoutOption[0]);

            if (num3 >= 0f && !Mathf.Approximately(this.m_AgentClimb.floatValue - num3, 0f))
            {
                this.m_AgentClimb.floatValue = num3;
            }
            if (this.m_AgentClimb.floatValue >= this.m_AgentHeight.floatValue)
            {
                EditorGUILayout.HelpBox("Step height should be less than agent height.\nClamping step height to " + this.m_AgentHeight.floatValue + ".", MessageType.Warning);
            }
            float floatValue = this.m_CellSize.floatValue;
            float num4       = floatValue * 0.5f;
            int   num5       = (int)Mathf.Ceil(this.m_AgentClimb.floatValue / num4);
            float num6       = Mathf.Tan(this.m_AgentSlope.floatValue / 180f * 3.14159274f) * floatValue;
            int   num7       = (int)Mathf.Ceil(num6 * 2f / num4);

            if (num7 > num5)
            {
                float f    = (float)num5 * num4 / (floatValue * 2f);
                float num8 = Mathf.Atan(f) / 3.14159274f * 180f;
                float num9 = (float)(num7 - 1) * num4;
                EditorGUILayout.HelpBox(string.Concat(new string[]
                {
                    "Step Height conflicts with Max Slope. This makes some slopes unwalkable.\nConsider decreasing Max Slope to < ",
                    num8.ToString("0.0"),
                    " degrees.\nOr, increase Step Height to > ",
                    num9.ToString("0.00"),
                    "."
                }), MessageType.Warning);
            }
            EditorGUILayout.Space();
            EditorGUILayout.LabelField(NavMeshEditorWindow.s_Styles.m_OffmeshHeader, EditorStyles.boldLabel, new GUILayoutOption[0]);
            bool flag = !InternalEditorUtility.HasProFeaturesEnabled();

            if (flag)
            {
                EditorGUILayout.HelpBox("This is only available in the Pro version of Unity.", MessageType.Warning);
                if (this.m_LedgeDropHeight.floatValue != 0f)
                {
                    this.m_LedgeDropHeight.floatValue = 0f;
                }
                if (this.m_MaxJumpAcrossDistance.floatValue != 0f)
                {
                    this.m_MaxJumpAcrossDistance.floatValue = 0f;
                }
                GUI.enabled = false;
            }
            float num10 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentDropContent, this.m_LedgeDropHeight.floatValue, new GUILayoutOption[0]);

            if (num10 >= 0f && !Mathf.Approximately(num10 - this.m_LedgeDropHeight.floatValue, 0f))
            {
                this.m_LedgeDropHeight.floatValue = num10;
            }
            float num11 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_AgentJumpContent, this.m_MaxJumpAcrossDistance.floatValue, new GUILayoutOption[0]);

            if (num11 >= 0f && !Mathf.Approximately(num11 - this.m_MaxJumpAcrossDistance.floatValue, 0f))
            {
                this.m_MaxJumpAcrossDistance.floatValue = num11;
            }
            if (flag)
            {
                GUI.enabled = true;
            }
            EditorGUILayout.Space();
            this.m_Advanced = GUILayout.Toggle(this.m_Advanced, NavMeshEditorWindow.s_Styles.m_AdvancedHeader, EditorStyles.foldout, new GUILayoutOption[0]);
            if (this.m_Advanced)
            {
                EditorGUI.indentLevel++;
                bool flag2 = EditorGUILayout.Toggle(NavMeshEditorWindow.s_Styles.m_ManualCellSizeContent, this.m_ManualCellSize.boolValue, new GUILayoutOption[0]);
                if (flag2 != this.m_ManualCellSize.boolValue)
                {
                    this.m_ManualCellSize.boolValue = flag2;
                    if (!flag2)
                    {
                        this.m_CellSize.floatValue = 2f * this.m_AgentRadius.floatValue / 6f;
                    }
                }
                EditorGUI.BeginDisabledGroup(!this.m_ManualCellSize.boolValue);
                EditorGUI.indentLevel++;
                float num12 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_CellSizeContent, this.m_CellSize.floatValue, new GUILayoutOption[0]);
                if (num12 > 0f && !Mathf.Approximately(num12 - this.m_CellSize.floatValue, 0f))
                {
                    this.m_CellSize.floatValue = Math.Max(0.01f, num12);
                }
                if (num12 < 0.01f)
                {
                    EditorGUILayout.HelpBox("The voxel size should be larger than 0.01.", MessageType.Warning);
                }
                float num13 = (this.m_CellSize.floatValue <= 0f) ? 0f : (this.m_AgentRadius.floatValue / this.m_CellSize.floatValue);
                EditorGUILayout.LabelField(" ", num13.ToString("0.00") + " voxels per agent radius", EditorStyles.miniLabel, new GUILayoutOption[0]);
                if (this.m_ManualCellSize.boolValue)
                {
                    float num14 = this.m_CellSize.floatValue * 0.5f;
                    if ((int)Mathf.Floor(this.m_AgentHeight.floatValue / num14) > 250)
                    {
                        EditorGUILayout.HelpBox("The number of voxels per agent height is too high. This will reduce the accuracy of the navmesh. Consider using voxel size of at least " + (this.m_AgentHeight.floatValue / 250f / 0.5f).ToString("0.000") + ".", MessageType.Warning);
                    }
                    if (num13 < 1f)
                    {
                        EditorGUILayout.HelpBox("The number of voxels per agent radius is too small. The agent may not avoid walls and ledges properly. Consider using voxel size of at least " + (this.m_AgentRadius.floatValue / 2f).ToString("0.000") + " (2 voxels per agent radius).", MessageType.Warning);
                    }
                    else
                    {
                        if (num13 > 8f)
                        {
                            EditorGUILayout.HelpBox("The number of voxels per agent radius is too high. It can cause excessive build times. Consider using voxel size closer to " + (this.m_AgentRadius.floatValue / 8f).ToString("0.000") + " (8 voxels per radius).", MessageType.Warning);
                        }
                    }
                }
                if (this.m_ManualCellSize.boolValue)
                {
                    EditorGUILayout.HelpBox("Voxel size controls how accurately the navigation mesh is generated from the level geometry. A good voxel size is 2-4 voxels per agent radius. Making voxel size smaller will increase build time.", MessageType.None);
                }
                EditorGUI.indentLevel--;
                EditorGUI.EndDisabledGroup();
                EditorGUILayout.Space();
                float num15 = EditorGUILayout.FloatField(NavMeshEditorWindow.s_Styles.m_MinRegionAreaContent, this.m_MinRegionArea.floatValue, new GUILayoutOption[0]);
                if (num15 >= 0f && num15 != this.m_MinRegionArea.floatValue)
                {
                    this.m_MinRegionArea.floatValue = num15;
                }
                EditorGUILayout.Space();
                bool flag3 = EditorGUILayout.Toggle(NavMeshEditorWindow.s_Styles.m_AgentPlacementContent, this.m_AccuratePlacement.boolValue, new GUILayoutOption[0]);
                if (flag3 != this.m_AccuratePlacement.boolValue)
                {
                    this.m_AccuratePlacement.boolValue = flag3;
                }
                EditorGUI.indentLevel--;
            }
        }
        public void RenderReflections(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle outputTexture, ScriptableRenderContext renderContext, uint frameCount)
        {
            // First thing to check is: Do we have a valid ray-tracing environment?
            HDRaytracingEnvironment rtEnvironement = m_RaytracingManager.CurrentEnvironment();
            BlueNoise        blueNoise             = m_RaytracingManager.GetBlueNoiseManager();
            ComputeShader    bilateralFilter       = m_PipelineAsset.renderPipelineResources.shaders.reflectionBilateralFilterCS;
            RaytracingShader reflectionShader      = m_PipelineAsset.renderPipelineResources.shaders.reflectionRaytracing;
            bool             missingResources      = rtEnvironement == null || blueNoise == null || bilateralFilter == null || reflectionShader == null ||
                                                     m_PipelineResources.textures.owenScrambledTex == null || m_PipelineResources.textures.scramblingTex == null;

            // Try to grab the acceleration structure and the list of HD lights for the target camera
            RaytracingAccelerationStructure accelerationStructure = m_RaytracingManager.RequestAccelerationStructure(hdCamera);
            HDRaytracingLightCluster        lightCluster          = m_RaytracingManager.RequestLightCluster(hdCamera);

            // If no acceleration structure available, end it now
            if (accelerationStructure == null || lightCluster == null || missingResources)
            {
                return;
            }

            // Compute the actual resolution that is needed base on the quality
            string targetRayGen = "";

            switch (rtEnvironement.reflQualityMode)
            {
            case HDRaytracingEnvironment.ReflectionsQuality.QuarterRes:
            {
                targetRayGen = m_RayGenHalfResName;
            };
                break;

            case HDRaytracingEnvironment.ReflectionsQuality.Integration:
            {
                targetRayGen = m_RayGenIntegrationName;
            };
                break;
            }

            // Define the shader pass to use for the reflection pass
            cmd.SetRaytracingShaderPass(reflectionShader, "ReflectionDXR");

            // Set the acceleration structure for the pass
            cmd.SetRaytracingAccelerationStructure(reflectionShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure);

            // Inject the ray-tracing sampling data
            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._OwenScrambledTexture, m_PipelineResources.textures.owenScrambledTex);
            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex);

            // Global reflection parameters
            cmd.SetRaytracingFloatParams(reflectionShader, HDShaderIDs._RaytracingIntensityClamp, rtEnvironement.reflClampValue);
            cmd.SetRaytracingFloatParams(reflectionShader, HDShaderIDs._RaytracingReflectionMinSmoothness, rtEnvironement.reflMinSmoothness);
            cmd.SetRaytracingFloatParams(reflectionShader, HDShaderIDs._RaytracingReflectionMaxDistance, rtEnvironement.reflBlendDistance);

            // Inject the ray generation data
            cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayBias, rtEnvironement.rayBias);
            cmd.SetGlobalFloat(HDShaderIDs._RaytracingRayMaxLength, rtEnvironement.reflRayLength);
            cmd.SetRaytracingIntParams(reflectionShader, HDShaderIDs._RaytracingNumSamples, rtEnvironement.reflNumMaxSamples);
            int frameIndex = hdCamera.IsTAAEnabled() ? hdCamera.taaFrameIndex : (int)frameCount % 8;

            cmd.SetGlobalInt(HDShaderIDs._RaytracingFrameIndex, frameIndex);

            // Set the data for the ray generation
            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._SsrLightingTextureRW, m_LightingTexture);
            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._SsrHitPointTexture, m_HitPdfTexture);
            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());

            // Set ray count tex
            cmd.SetRaytracingIntParam(reflectionShader, HDShaderIDs._RayCountEnabled, m_RaytracingManager.rayCountManager.rayCountEnabled);
            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._RayCountTexture, m_RaytracingManager.rayCountManager.rayCountTex);

            // Compute the pixel spread value
            float pixelSpreadAngle = Mathf.Atan(2.0f * Mathf.Tan(hdCamera.camera.fieldOfView * Mathf.PI / 360.0f) / Mathf.Min(hdCamera.actualWidth, hdCamera.actualHeight));

            cmd.SetRaytracingFloatParam(reflectionShader, HDShaderIDs._RaytracingPixelSpreadAngle, pixelSpreadAngle);

            // LightLoop data
            cmd.SetGlobalBuffer(HDShaderIDs._RaytracingLightCluster, lightCluster.GetCluster());
            cmd.SetGlobalBuffer(HDShaderIDs._LightDatasRT, lightCluster.GetLightDatas());
            cmd.SetGlobalVector(HDShaderIDs._MinClusterPos, lightCluster.GetMinClusterPos());
            cmd.SetGlobalVector(HDShaderIDs._MaxClusterPos, lightCluster.GetMaxClusterPos());
            cmd.SetGlobalInt(HDShaderIDs._LightPerCellCount, rtEnvironement.maxNumLightsPercell);
            cmd.SetGlobalInt(HDShaderIDs._PunctualLightCountRT, lightCluster.GetPunctualLightCount());
            cmd.SetGlobalInt(HDShaderIDs._AreaLightCountRT, lightCluster.GetAreaLightCount());

            // Evaluate the clear coat mask texture based on the lit shader mode
            RenderTargetIdentifier clearCoatMaskTexture = hdCamera.frameSettings.litShaderMode == LitShaderMode.Deferred ? m_GbufferManager.GetBuffersRTI()[2] : Texture2D.blackTexture;

            cmd.SetRaytracingTextureParam(reflectionShader, targetRayGen, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMaskTexture);

            // Set the data for the ray miss
            cmd.SetRaytracingTextureParam(reflectionShader, m_MissShaderName, HDShaderIDs._SkyTexture, m_SkyManager.skyReflection);

            // Compute the actual resolution that is needed base on the quality
            uint widthResolution = 1, heightResolution = 1;

            switch (rtEnvironement.reflQualityMode)
            {
            case HDRaytracingEnvironment.ReflectionsQuality.QuarterRes:
            {
                widthResolution  = (uint)hdCamera.actualWidth / 2;
                heightResolution = (uint)hdCamera.actualHeight / 2;
            };
                break;

            case HDRaytracingEnvironment.ReflectionsQuality.Integration:
            {
                widthResolution  = (uint)hdCamera.actualWidth;
                heightResolution = (uint)hdCamera.actualHeight;
            };
                break;
            }

            // Run the calculus
            cmd.DispatchRays(reflectionShader, targetRayGen, widthResolution, heightResolution, 1);

            using (new ProfilingSample(cmd, "Filter Reflection", CustomSamplerId.RaytracingFilterReflection.GetSampler()))
            {
                switch (rtEnvironement.reflQualityMode)
                {
                case HDRaytracingEnvironment.ReflectionsQuality.QuarterRes:
                {
                    // Fetch the right filter to use
                    int currentKernel = bilateralFilter.FindKernel("RaytracingReflectionFilter");

                    // Inject all the parameters for the compute
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._SsrLightingTextureRW, m_LightingTexture);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._SsrHitPointTexture, m_HitPdfTexture);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_NoiseTexture", blueNoise.textureArray16RGB);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_VarianceTexture", m_VarianceBuffer);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MinColorRangeTexture", m_MinBoundBuffer);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MaxColorRangeTexture", m_MaxBoundBuffer);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_RaytracingReflectionTexture", outputTexture);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._ScramblingTexture, m_PipelineResources.textures.scramblingTex);
                    cmd.SetComputeIntParam(bilateralFilter, HDShaderIDs._SpatialFilterRadius, rtEnvironement.reflSpatialFilterRadius);

                    // Texture dimensions
                    int texWidth  = outputTexture.rt.width;
                    int texHeight = outputTexture.rt.width;

                    // Evaluate the dispatch parameters
                    int areaTileSize = 8;
                    int numTilesXHR  = (texWidth / 2 + (areaTileSize - 1)) / areaTileSize;
                    int numTilesYHR  = (texHeight / 2 + (areaTileSize - 1)) / areaTileSize;

                    // Bind the right texture for clear coat support
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._SsrClearCoatMaskTexture, clearCoatMaskTexture);

                    // Compute the texture
                    cmd.DispatchCompute(bilateralFilter, currentKernel, numTilesXHR, numTilesYHR, 1);

                    int numTilesXFR = (texWidth + (areaTileSize - 1)) / areaTileSize;
                    int numTilesYFR = (texHeight + (areaTileSize - 1)) / areaTileSize;

                    RTHandleSystem.RTHandle history = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.RaytracedReflection)
                                                      ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.RaytracedReflection, ReflectionHistoryBufferAllocatorFunction, 1);

                    // Fetch the right filter to use
                    currentKernel = bilateralFilter.FindKernel("TemporalAccumulationFilter");
                    cmd.SetComputeFloatParam(bilateralFilter, HDShaderIDs._TemporalAccumuationWeight, rtEnvironement.reflTemporalAccumulationWeight);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._AccumulatedFrameTexture, history);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, HDShaderIDs._CurrentFrameTexture, outputTexture);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MinColorRangeTexture", m_MinBoundBuffer);
                    cmd.SetComputeTextureParam(bilateralFilter, currentKernel, "_MaxColorRangeTexture", m_MaxBoundBuffer);
                    cmd.DispatchCompute(bilateralFilter, currentKernel, numTilesXFR, numTilesYFR, 1);
                }
                break;

                case HDRaytracingEnvironment.ReflectionsQuality.Integration:
                {
                    HDUtils.BlitCameraTexture(cmd, hdCamera, m_LightingTexture, outputTexture);
                }
                break;
                }
            }
        }
Exemple #15
0
 float FovForHeightAndDistance(float height, float distance)
 {
     return(2f * Mathf.Atan(height * 0.5f / distance) * Mathf.Rad2Deg);
 }
Exemple #16
0
 //Calculate thetaOne by IM1
 public void thetaOneCalc()
 {
     this.thetaOne = Mathf.Atan((this.obj.transform.position.y - explosionPoint.y) / Mathf.Sqrt(Mathf.Pow(this.obj.transform.position.x - explosionPoint.x, 2) + Mathf.Pow(this.obj.transform.position.z - explosionPoint.z, 2)));
 }
    void OnWizardCreate()
    {
        GameObject newCone = new GameObject("Cone");

        if (openingAngle > 0 && openingAngle < 180)
        {
            radiusTop    = 0;
            radiusBottom = length * Mathf.Tan(openingAngle * Mathf.Deg2Rad / 2);
        }
        string meshName = newCone.name + numVertices + "v" + radiusTop + "t" + radiusBottom + "b" + length + "l" +
                          length + (outside ? "o" : "") + (inside ? "i" : "");
        string meshPrefabPath = "Assets/Editor/" + meshName + ".asset";
        Mesh   mesh           = (Mesh)AssetDatabase.LoadAssetAtPath(meshPrefabPath, typeof(Mesh));

        if (mesh == null)
        {
            mesh      = new Mesh();
            mesh.name = meshName;
            // can't access Camera.current
            //newCone.transform.position = Camera.current.transform.position + Camera.current.transform.forward * 5.0f;
            int       multiplier = (outside ? 1 : 0) + (inside ? 1 : 0);
            int       offset     = (outside && inside ? 2 * numVertices : 0);
            Vector3[] vertices   = new Vector3[2 * multiplier * numVertices]; // 0..n-1: top, n..2n-1: bottom
            Vector3[] normals    = new Vector3[2 * multiplier * numVertices];
            Vector2[] uvs        = new Vector2[2 * multiplier * numVertices];
            int[]     tris;
            float     slope    = Mathf.Atan((radiusBottom - radiusTop) / length); // (rad difference)/height
            float     slopeSin = Mathf.Sin(slope);
            float     slopeCos = Mathf.Cos(slope);
            int       i;

            for (i = 0; i < numVertices; i++)
            {
                float angle        = 2 * Mathf.PI * i / numVertices;
                float angleSin     = Mathf.Sin(angle);
                float angleCos     = Mathf.Cos(angle);
                float angleHalf    = 2 * Mathf.PI * (i + 0.5f) / numVertices; // for degenerated normals at cone tips
                float angleHalfSin = Mathf.Sin(angleHalf);
                float angleHalfCos = Mathf.Cos(angleHalf);

                vertices[i] = new Vector3(radiusTop * angleCos, radiusTop * angleSin, 0);
                vertices[i + numVertices] = new Vector3(radiusBottom * angleCos, radiusBottom * angleSin, length);

                if (radiusTop == 0)
                {
                    normals[i] = new Vector3(angleHalfCos * slopeCos, angleHalfSin * slopeCos, -slopeSin);
                }
                else
                {
                    normals[i] = new Vector3(angleCos * slopeCos, angleSin * slopeCos, -slopeSin);
                }
                if (radiusBottom == 0)
                {
                    normals[i + numVertices] = new Vector3(angleHalfCos * slopeCos, angleHalfSin * slopeCos, -slopeSin);
                }
                else
                {
                    normals[i + numVertices] = new Vector3(angleCos * slopeCos, angleSin * slopeCos, -slopeSin);
                }

                uvs[i] = new Vector2(1.0f * i / numVertices, 1);
                uvs[i + numVertices] = new Vector2(1.0f * i / numVertices, 0);

                if (outside && inside)
                {
                    // vertices and uvs are identical on inside and outside, so just copy
                    vertices[i + 2 * numVertices] = vertices[i];
                    vertices[i + 3 * numVertices] = vertices[i + numVertices];
                    uvs[i + 2 * numVertices]      = uvs[i];
                    uvs[i + 3 * numVertices]      = uvs[i + numVertices];
                }
                if (inside)
                {
                    // invert normals
                    normals[i + offset] = -normals[i];
                    normals[i + numVertices + offset] = -normals[i + numVertices];
                }
            }
            mesh.vertices = vertices;
            mesh.normals  = normals;
            mesh.uv       = uvs;

            // create triangles
            // here we need to take care of point order, depending on inside and outside
            int cnt = 0;
            if (radiusTop == 0)
            {
                // top cone
                tris = new int[numVertices * 3 * multiplier];
                if (outside)
                {
                    for (i = 0; i < numVertices; i++)
                    {
                        tris[cnt++] = i + numVertices;
                        tris[cnt++] = i;
                        if (i == numVertices - 1)
                        {
                            tris[cnt++] = numVertices;
                        }
                        else
                        {
                            tris[cnt++] = i + 1 + numVertices;
                        }
                    }
                }
                if (inside)
                {
                    for (i = offset; i < numVertices + offset; i++)
                    {
                        tris[cnt++] = i;
                        tris[cnt++] = i + numVertices;
                        if (i == numVertices - 1 + offset)
                        {
                            tris[cnt++] = numVertices + offset;
                        }
                        else
                        {
                            tris[cnt++] = i + 1 + numVertices;
                        }
                    }
                }
            }
            else if (radiusBottom == 0)
            {
                // bottom cone
                tris = new int[numVertices * 3 * multiplier];
                if (outside)
                {
                    for (i = 0; i < numVertices; i++)
                    {
                        tris[cnt++] = i;
                        if (i == numVertices - 1)
                        {
                            tris[cnt++] = 0;
                        }
                        else
                        {
                            tris[cnt++] = i + 1;
                        }
                        tris[cnt++] = i + numVertices;
                    }
                }
                if (inside)
                {
                    for (i = offset; i < numVertices + offset; i++)
                    {
                        if (i == numVertices - 1 + offset)
                        {
                            tris[cnt++] = offset;
                        }
                        else
                        {
                            tris[cnt++] = i + 1;
                        }
                        tris[cnt++] = i;
                        tris[cnt++] = i + numVertices;
                    }
                }
            }
            else
            {
                // truncated cone
                tris = new int[numVertices * 6 * multiplier];
                if (outside)
                {
                    for (i = 0; i < numVertices; i++)
                    {
                        int ip1 = i + 1;
                        if (ip1 == numVertices)
                        {
                            ip1 = 0;
                        }

                        tris[cnt++] = i;
                        tris[cnt++] = ip1;
                        tris[cnt++] = i + numVertices;

                        tris[cnt++] = ip1 + numVertices;
                        tris[cnt++] = i + numVertices;
                        tris[cnt++] = ip1;
                    }
                }
                if (inside)
                {
                    for (i = offset; i < numVertices + offset; i++)
                    {
                        int ip1 = i + 1;
                        if (ip1 == numVertices + offset)
                        {
                            ip1 = offset;
                        }

                        tris[cnt++] = ip1;
                        tris[cnt++] = i;
                        tris[cnt++] = i + numVertices;

                        tris[cnt++] = i + numVertices;
                        tris[cnt++] = ip1 + numVertices;
                        tris[cnt++] = ip1;
                    }
                }
            }
            mesh.triangles = tris;
            AssetDatabase.CreateAsset(mesh, meshPrefabPath);
            AssetDatabase.SaveAssets();
        }

        MeshFilter mf = newCone.AddComponent <MeshFilter>();

        mf.mesh = mesh;

        newCone.AddComponent <MeshRenderer>();

        if (addCollider)
        {
            MeshCollider mc = newCone.AddComponent <MeshCollider>();
            mc.sharedMesh = mf.sharedMesh;
        }

        Selection.activeObject = newCone;
    }
Exemple #18
0
    public override void Update(Camera mainCamera)
    {
        if (!hasCameraDeviceOpened)
        {
            return;
        }

        if (!OVRPlugin.SetHandNodePoseStateLatency(OVRManager.instance.handPoseStateLatency))
        {
            Debug.LogWarning("HandPoseStateLatency is invalid. Expect a value between 0.0 to 0.5, get " + OVRManager.instance.handPoseStateLatency);
        }

        directCompositionCamera.clearFlags      = mainCamera.clearFlags;
        directCompositionCamera.backgroundColor = mainCamera.backgroundColor;
        directCompositionCamera.cullingMask     = mainCamera.cullingMask & (~OVRManager.instance.extraHiddenLayers);
        directCompositionCamera.nearClipPlane   = mainCamera.nearClipPlane;
        directCompositionCamera.farClipPlane    = mainCamera.farClipPlane;

        if (OVRMixedReality.useFakeExternalCamera || OVRPlugin.GetExternalCameraCount() == 0)
        {
            OVRPose trackingSpacePose = new OVRPose();
            trackingSpacePose.position          = OVRMixedReality.fakeCameraPositon;
            trackingSpacePose.orientation       = OVRMixedReality.fakeCameraRotation;
            directCompositionCamera.fieldOfView = OVRMixedReality.fakeCameraFov;
            directCompositionCamera.aspect      = OVRMixedReality.fakeCameraAspect;
            if (cameraInTrackingSpace)
            {
                directCompositionCamera.transform.FromOVRPose(trackingSpacePose, true);
            }
            else
            {
                OVRPose worldSpacePose = new OVRPose();
                worldSpacePose = OVRExtensions.ToWorldSpacePose(trackingSpacePose);
                directCompositionCamera.transform.FromOVRPose(worldSpacePose);
            }
        }
        else
        {
            OVRPlugin.CameraExtrinsics extrinsics;
            OVRPlugin.CameraIntrinsics intrinsics;

            // So far, only support 1 camera for MR and always use camera index 0
            if (OVRPlugin.GetMixedRealityCameraInfo(0, out extrinsics, out intrinsics))
            {
                float fovY   = Mathf.Atan(intrinsics.FOVPort.UpTan) * Mathf.Rad2Deg * 2;
                float aspect = intrinsics.FOVPort.LeftTan / intrinsics.FOVPort.UpTan;
                directCompositionCamera.fieldOfView = fovY;
                directCompositionCamera.aspect      = aspect;
                if (cameraInTrackingSpace)
                {
                    OVRPose trackingSpacePose = ComputeCameraTrackingSpacePose(extrinsics);
                    directCompositionCamera.transform.FromOVRPose(trackingSpacePose, true);
                }
                else
                {
                    OVRPose worldSpacePose = ComputeCameraWorldSpacePose(extrinsics);
                    directCompositionCamera.transform.FromOVRPose(worldSpacePose);
                }
            }
            else
            {
                Debug.LogWarning("Failed to get external camera information");
            }
        }

        if (hasCameraDeviceOpened)
        {
            if (boundaryMeshMaskTexture == null || boundaryMeshMaskTexture.width != Screen.width || boundaryMeshMaskTexture.height != Screen.height)
            {
                boundaryMeshMaskTexture = new RenderTexture(Screen.width, Screen.height, 0, RenderTextureFormat.R8);
                boundaryMeshMaskTexture.Create();
            }
            UpdateCameraFramePlaneObject(mainCamera, directCompositionCamera, boundaryMeshMaskTexture);
            directCompositionCamera.GetComponent <OVRCameraFrameCompositionManager>().boundaryMeshMaskTexture = boundaryMeshMaskTexture;
        }
    }
    public override void Update(GameObject gameObject, Camera mainCamera)
    {
        RefreshCameraObjects(gameObject, mainCamera);

        OVRPlugin.SetHandNodePoseStateLatency(0.0);             // the HandNodePoseStateLatency doesn't apply to the external composition. Always enforce it to 0.0

#if OVR_ANDROID_MRC
        RefreshAudioFilter();

        int drawTextureIndex = (frameIndex / 2) % 2;
        int castTextureIndex = 1 - drawTextureIndex;

        backgroundCamera.enabled = (frameIndex % 2) == 0;
        foregroundCamera.enabled = (frameIndex % 2) == 1;

        if (frameIndex % 2 == 0)
        {
            if (lastMrcEncodeFrameSyncId != -1)
            {
                OVRPlugin.Media.SyncMrcFrame(lastMrcEncodeFrameSyncId);
                lastMrcEncodeFrameSyncId = -1;
            }
            lastMrcEncodeFrameSyncId = CastMrcFrame(castTextureIndex);
            SetCameraTargetTexture(drawTextureIndex);
        }

        ++frameIndex;
#endif

        backgroundCamera.clearFlags      = mainCamera.clearFlags;
        backgroundCamera.backgroundColor = mainCamera.backgroundColor;
        backgroundCamera.cullingMask     = mainCamera.cullingMask & (~OVRManager.instance.extraHiddenLayers);
        backgroundCamera.nearClipPlane   = mainCamera.nearClipPlane;
        backgroundCamera.farClipPlane    = mainCamera.farClipPlane;

        foregroundCamera.cullingMask   = mainCamera.cullingMask & (~OVRManager.instance.extraHiddenLayers);
        foregroundCamera.nearClipPlane = mainCamera.nearClipPlane;
        foregroundCamera.farClipPlane  = mainCamera.farClipPlane;

        if (OVRMixedReality.useFakeExternalCamera || OVRPlugin.GetExternalCameraCount() == 0)
        {
            OVRPose worldSpacePose    = new OVRPose();
            OVRPose trackingSpacePose = new OVRPose();
            trackingSpacePose.position = OVRManager.instance.trackingOriginType == OVRManager.TrackingOrigin.EyeLevel ?
                                         OVRMixedReality.fakeCameraEyeLevelPosition :
                                         OVRMixedReality.fakeCameraFloorLevelPosition;
            trackingSpacePose.orientation = OVRMixedReality.fakeCameraRotation;
            worldSpacePose = OVRExtensions.ToWorldSpacePose(trackingSpacePose);

            backgroundCamera.fieldOfView = OVRMixedReality.fakeCameraFov;
            backgroundCamera.aspect      = OVRMixedReality.fakeCameraAspect;
            foregroundCamera.fieldOfView = OVRMixedReality.fakeCameraFov;
            foregroundCamera.aspect      = OVRMixedReality.fakeCameraAspect;

            if (cameraInTrackingSpace)
            {
                backgroundCamera.transform.FromOVRPose(trackingSpacePose, true);
                foregroundCamera.transform.FromOVRPose(trackingSpacePose, true);
            }
            else
            {
                backgroundCamera.transform.FromOVRPose(worldSpacePose);
                foregroundCamera.transform.FromOVRPose(worldSpacePose);
            }
        }
        else
        {
            OVRPlugin.CameraExtrinsics extrinsics;
            OVRPlugin.CameraIntrinsics intrinsics;
            OVRPlugin.Posef            calibrationRawPose;

            // So far, only support 1 camera for MR and always use camera index 0
            if (OVRPlugin.GetMixedRealityCameraInfo(0, out extrinsics, out intrinsics, out calibrationRawPose))
            {
                float fovY   = Mathf.Atan(intrinsics.FOVPort.UpTan) * Mathf.Rad2Deg * 2;
                float aspect = intrinsics.FOVPort.LeftTan / intrinsics.FOVPort.UpTan;
                backgroundCamera.fieldOfView = fovY;
                backgroundCamera.aspect      = aspect;
                foregroundCamera.fieldOfView = fovY;
                foregroundCamera.aspect      = intrinsics.FOVPort.LeftTan / intrinsics.FOVPort.UpTan;

                if (cameraInTrackingSpace)
                {
                    OVRPose trackingSpacePose = ComputeCameraTrackingSpacePose(extrinsics, calibrationRawPose);
                    backgroundCamera.transform.FromOVRPose(trackingSpacePose, true);
                    foregroundCamera.transform.FromOVRPose(trackingSpacePose, true);
                }
                else
                {
                    OVRPose worldSpacePose = ComputeCameraWorldSpacePose(extrinsics, calibrationRawPose);
                    backgroundCamera.transform.FromOVRPose(worldSpacePose);
                    foregroundCamera.transform.FromOVRPose(worldSpacePose);
                }
            }
            else
            {
                Debug.LogError("Failed to get external camera information");
                return;
            }
        }

        Vector3 headToExternalCameraVec = mainCamera.transform.position - foregroundCamera.transform.position;
        float   clipDistance            = Vector3.Dot(headToExternalCameraVec, foregroundCamera.transform.forward);
        foregroundCamera.farClipPlane = Mathf.Max(foregroundCamera.nearClipPlane + 0.001f, clipDistance);
    }
Exemple #20
0
    private void CreateWarning()
    {
        Destroy(this.gameObject, 10f);
        ParticleSystem ps;

        warning_temp = Instantiate(warning_effect, this.transform.position, Quaternion.identity);
        ps           = warning_temp.GetComponent <ParticleSystem>();
        var simulate = ps.main;

        simulate.simulationSpeed          = 1 / 2f;
        warning_temp.transform.localScale = new Vector3(40, 0.7f, 0.7f);
        if (dir.x > 0)
        {
            warning_temp.transform.rotation = Quaternion.Euler(0, 0, Mathf.Rad2Deg * Mathf.Atan((dir.y) / dir.x));
        }
        else
        {
            warning_temp.transform.rotation = Quaternion.Euler(0, 0, 180 + Mathf.Rad2Deg * Mathf.Atan((dir.y) / dir.x));
        }

        switch (UpLoadData.boss_level)
        {
        case 0:
            NetworkManager.instance.InstantiateBossSkill(UpLoadData.boss_index, 26, warning_temp.transform, 2f, true, false);
            break;

        case 1:
            NetworkManager.instance.InstantiateBossSkill(UpLoadData.boss_index, 26, warning_temp.transform, 1.8f, true, false);
            break;

        case 2:
            NetworkManager.instance.InstantiateBossSkill(UpLoadData.boss_index, 26, warning_temp.transform, 1f, true, false);
            break;

        case 3:
            NetworkManager.instance.InstantiateBossSkill(UpLoadData.boss_index, 26, warning_temp.transform, 0.5f, true, false);
            break;
        }

        switch (UpLoadData.boss_level)
        {
        case 0:
            Destroy(warning_temp, 2f);
            break;

        case 1:
            Destroy(warning_temp, 1.8f);
            break;

        case 2:
            Destroy(warning_temp, 1f);
            break;

        case 3:
            Destroy(warning_temp, 0.5f);
            break;
        }
    }
        public void VoxelizeInput(Pathfinding.Util.GraphTransform graphTransform, Bounds graphSpaceBounds)
        {
            AstarProfiler.StartProfile("Build Navigation Mesh");

            AstarProfiler.StartProfile("Voxelizing - Step 1");

            // Transform from voxel space to graph space.
            // then scale from voxel space (one unit equals one voxel)
            // Finally add min
            Matrix4x4 voxelMatrix = Matrix4x4.TRS(graphSpaceBounds.min, Quaternion.identity, Vector3.one) * Matrix4x4.Scale(new Vector3(cellSize, cellHeight, cellSize));

            transformVoxel2Graph = new Pathfinding.Util.GraphTransform(voxelMatrix);

            // Transform from voxel space to world space
            // add half a voxel to fix rounding
            transform = graphTransform * voxelMatrix * Matrix4x4.TRS(new Vector3(0.5f, 0, 0.5f), Quaternion.identity, Vector3.one);

            int maximumVoxelYCoord = (int)(graphSpaceBounds.size.y / cellHeight);

            AstarProfiler.EndProfile("Voxelizing - Step 1");

            AstarProfiler.StartProfile("Voxelizing - Step 2 - Init");

            // Cosine of the slope limit in voxel space (some tweaks are needed because the voxel space might be stretched out along the y axis)
            float slopeLimit = Mathf.Cos(Mathf.Atan(Mathf.Tan(maxSlope * Mathf.Deg2Rad) * (cellSize / cellHeight)));

            // Temporary arrays used for rasterization
            float[] vTris    = new float[3 * 3];
            float[] vOut     = new float[7 * 3];
            float[] vRow     = new float[7 * 3];
            float[] vCellOut = new float[7 * 3];
            float[] vCell    = new float[7 * 3];

            if (inputMeshes == null)
            {
                throw new System.NullReferenceException("inputMeshes not set");
            }

            // Find the largest lengths of vertex arrays and check for meshes which can be skipped
            int maxVerts = 0;

            for (int m = 0; m < inputMeshes.Count; m++)
            {
                maxVerts = System.Math.Max(inputMeshes[m].vertices.Length, maxVerts);
            }

            // Create buffer, here vertices will be stored multiplied with the local-to-voxel-space matrix
            var verts = new Vector3[maxVerts];

            AstarProfiler.EndProfile("Voxelizing - Step 2 - Init");

            AstarProfiler.StartProfile("Voxelizing - Step 2");

            // This loop is the hottest place in the whole rasterization process
            // it usually accounts for around 50% of the time
            for (int m = 0; m < inputMeshes.Count; m++)
            {
                RasterizationMesh mesh = inputMeshes[m];
                var meshMatrix         = mesh.matrix;

                // Flip the orientation of all faces if the mesh is scaled in such a way
                // that the face orientations would change
                // This happens for example if a mesh has a negative scale along an odd number of axes
                // e.g it happens for the scale (-1, 1, 1) but not for (-1, -1, 1) or (1,1,1)
                var flipOrientation = VectorMath.ReversesFaceOrientations(meshMatrix);

                Vector3[] vs         = mesh.vertices;
                int[]     tris       = mesh.triangles;
                int       trisLength = tris.Length;

                // Transform vertices first to world space and then to voxel space
                for (int i = 0; i < vs.Length; i++)
                {
                    verts[i] = transform.InverseTransform(meshMatrix.MultiplyPoint3x4(vs[i]));
                }

                int mesharea = mesh.area;

                for (int i = 0; i < trisLength; i += 3)
                {
                    Vector3 p1 = verts[tris[i]];
                    Vector3 p2 = verts[tris[i + 1]];
                    Vector3 p3 = verts[tris[i + 2]];

                    if (flipOrientation)
                    {
                        var tmp = p1;
                        p1 = p3;
                        p3 = tmp;
                    }

                    int minX = (int)(Utility.Min(p1.x, p2.x, p3.x));
                    int minZ = (int)(Utility.Min(p1.z, p2.z, p3.z));

                    int maxX = (int)System.Math.Ceiling(Utility.Max(p1.x, p2.x, p3.x));
                    int maxZ = (int)System.Math.Ceiling(Utility.Max(p1.z, p2.z, p3.z));

                    minX = Mathf.Clamp(minX, 0, voxelArea.width - 1);
                    maxX = Mathf.Clamp(maxX, 0, voxelArea.width - 1);
                    minZ = Mathf.Clamp(minZ, 0, voxelArea.depth - 1);
                    maxZ = Mathf.Clamp(maxZ, 0, voxelArea.depth - 1);

                    // Check if the mesh is completely out of bounds
                    if (minX >= voxelArea.width || minZ >= voxelArea.depth || maxX <= 0 || maxZ <= 0)
                    {
                        continue;
                    }

                    Vector3 normal;

                    int area;

                    //AstarProfiler.StartProfile ("Rasterize...");

                    normal = Vector3.Cross(p2 - p1, p3 - p1);

                    float cosSlopeAngle = Vector3.Dot(normal.normalized, Vector3.up);

                    if (cosSlopeAngle < slopeLimit)
                    {
                        area = UnwalkableArea;
                    }
                    else
                    {
                        area = 1 + mesharea;
                    }

                    Utility.CopyVector(vTris, 0, p1);
                    Utility.CopyVector(vTris, 3, p2);
                    Utility.CopyVector(vTris, 6, p3);

                    for (int x = minX; x <= maxX; x++)
                    {
                        int nrow = clipper.ClipPolygon(vTris, 3, vOut, 1F, -x + 0.5F, 0);

                        if (nrow < 3)
                        {
                            continue;
                        }

                        nrow = clipper.ClipPolygon(vOut, nrow, vRow, -1F, x + 0.5F, 0);

                        if (nrow < 3)
                        {
                            continue;
                        }

                        float clampZ1 = vRow[2];
                        float clampZ2 = vRow[2];
                        for (int q = 1; q < nrow; q++)
                        {
                            float val = vRow[q * 3 + 2];
                            clampZ1 = System.Math.Min(clampZ1, val);
                            clampZ2 = System.Math.Max(clampZ2, val);
                        }

                        int clampZ1I = Mathf.Clamp((int)System.Math.Round(clampZ1), 0, voxelArea.depth - 1);
                        int clampZ2I = Mathf.Clamp((int)System.Math.Round(clampZ2), 0, voxelArea.depth - 1);


                        for (int z = clampZ1I; z <= clampZ2I; z++)
                        {
                            //AstarProfiler.StartFastProfile(1);
                            int ncell = clipper.ClipPolygon(vRow, nrow, vCellOut, 1F, -z + 0.5F, 2);

                            if (ncell < 3)
                            {
                                //AstarProfiler.EndFastProfile(1);
                                continue;
                            }

                            ncell = clipper.ClipPolygonY(vCellOut, ncell, vCell, -1F, z + 0.5F, 2);

                            if (ncell < 3)
                            {
                                //AstarProfiler.EndFastProfile(1);
                                continue;
                            }

                            //AstarProfiler.EndFastProfile(1);
                            //AstarProfiler.StartFastProfile(2);
                            float sMin = vCell[1];
                            float sMax = vCell[1];
                            for (int q = 1; q < ncell; q++)
                            {
                                float val = vCell[q * 3 + 1];
                                sMin = System.Math.Min(sMin, val);
                                sMax = System.Math.Max(sMax, val);
                            }

                            //AstarProfiler.EndFastProfile(2);
                            int maxi = (int)System.Math.Ceiling(sMax);

                            // Skip span if below or above the bounding box
                            if (maxi >= 0 && sMin <= maximumVoxelYCoord)
                            {
                                // Make sure mini >= 0
                                int mini = System.Math.Max(0, (int)sMin);

                                // Make sure the span is at least 1 voxel high
                                maxi = System.Math.Max(mini + 1, maxi);

                                voxelArea.AddLinkedSpan(z * voxelArea.width + x, (uint)mini, (uint)maxi, area, voxelWalkableClimb);
                            }
                        }
                    }
                }
                //AstarProfiler.EndFastProfile(0);
                //AstarProfiler.EndProfile ("Rasterize...");
            }
            AstarProfiler.EndProfile("Voxelizing - Step 2");
        }
Exemple #22
0
 /// <summary>
 /// Get back the FOV from the Projection matrix, to bypass a round number
 /// </summary>
 /// <param name="projection"></param>
 /// <returns></returns>
 float GetFOVFromProjectionMatrix(Matrix4x4 projection)
 {
     return(Mathf.Atan(1 / projection[1, 1]) * 2.0f);
 }
Exemple #23
0
        /// <summary>
        /// expend the camera by vertical.
        /// </summary>
        /// <param name="camera">Camera.</param>
        /// <param name="fScale">F scale.</param>
        static public void ExpendCameraByVertical(Camera camera, float fScale)
        {
            float a2 = Mathf.Atan(Mathf.Tan(camera.fieldOfView / 2 / 180 * Mathf.PI) * fScale);

            camera.fieldOfView = a2 / Mathf.PI * 180 * 2;
        }
    public override void Raycast(PointerEventData eventData, List <RaycastResult> resultAppendList)
    {
        base.Raycast(eventData, resultAppendList);

        toExclude.Clear();

        foreach (var result in resultAppendList)
        {
            var objImage = result.gameObject.GetComponent <Image>();
            if (!objImage)
            {
                continue;
            }
            if (!objImage.sprite)
            {
                continue;
            }

            var objAlphaCheck = result.gameObject.GetComponent <AlphaCheck>();
            if (SelectiveMode && !objAlphaCheck)
            {
                continue;
            }

            try
            {
                var objTrs = result.gameObject.transform as RectTransform;

                // Evaluating pointer position relative to object local space
                Vector3 pointerGPos;
                if (eventCamera)
                {
                    var   objPlane = new Plane(objTrs.forward, objTrs.position);
                    float distance;
                    var   cameraRay = eventCamera.ScreenPointToRay(eventData.position);
                    objPlane.Raycast(cameraRay, out distance);
                    pointerGPos = cameraRay.GetPoint(distance);
                }
                else
                {
                    pointerGPos = eventData.position;
                    float rotationCorrection = (-objTrs.forward.x * (pointerGPos.x - objTrs.position.x) - objTrs.forward.y * (pointerGPos.y - objTrs.position.y)) / objTrs.forward.z;
                    pointerGPos += new Vector3(0, 0, objTrs.position.z + rotationCorrection);
                }
                Vector3 pointerLPos = objTrs.InverseTransformPoint(pointerGPos);

                var  objTex = objImage.mainTexture as Texture2D;
                Rect texRect;
                // Case for sprites with redundant transparent areas (Unity trims them internally, so we have to handle that)
                if (objImage.sprite.textureRectOffset.sqrMagnitude > 0)
                {
                    texRect = objImage.sprite.packed ? new Rect(objImage.sprite.textureRect.xMin - objImage.sprite.textureRectOffset.x,
                                                                objImage.sprite.textureRect.yMin - objImage.sprite.textureRectOffset.y,
                                                                objImage.sprite.textureRect.width + objImage.sprite.textureRectOffset.x * 2f,
                                                                objImage.sprite.textureRect.height + objImage.sprite.textureRectOffset.y * 2f) : objImage.sprite.rect;
                }
                else
                {
                    texRect = objImage.sprite.textureRect;
                }
                var objSize = objTrs.rect.size;

                // Correcting objSize in case "preserve aspect" is enabled
                if (objImage.preserveAspect)
                {
                    if (objSize.x < objSize.y)
                    {
                        objSize.y = objSize.x * (texRect.height / texRect.width);
                    }
                    else
                    {
                        objSize.x = objSize.y * (texRect.width / texRect.height);
                    }

                    // Also we need to cut off empty object space
                    var halfPivot = new Vector2(Mathf.Abs(objTrs.pivot.x) == .5f ? 2 : 1, Mathf.Abs(objTrs.pivot.y) == .5f ? 2 : 1);
                    if (Mathf.Abs(pointerLPos.x * halfPivot.x) > objSize.x || Mathf.Abs(pointerLPos.y * halfPivot.y) > objSize.y)
                    {
                        toExclude.Add(result); continue;
                    }
                }

                // Evaluating texture coordinates of the targeted spot
                float texCorX = pointerLPos.x + objSize.x * objTrs.pivot.x;
                float texCorY = pointerLPos.y + objSize.y * objTrs.pivot.y;

                #region TILED_SLICED
                // Will be used if image has a border
                var borderTotalWidth  = objImage.sprite.border.x + objImage.sprite.border.z;
                var borderTotalHeight = objImage.sprite.border.y + objImage.sprite.border.w;
                var fillRect          = new Rect(objImage.sprite.border.x, objImage.sprite.border.y,
                                                 Mathf.Clamp(objSize.x - borderTotalWidth, 0f, Mathf.Infinity),
                                                 Mathf.Clamp(objSize.y - borderTotalHeight, 0f, Mathf.Infinity));
                var isInsideFillRect = objImage.hasBorder && fillRect.Contains(new Vector2(texCorX, texCorY));

                // Correcting texture coordinates in case image is tiled
                if (objImage.type == Image.Type.Tiled)
                {
                    if (isInsideFillRect)
                    {
                        if (!objImage.fillCenter)
                        {
                            toExclude.Add(result); continue;
                        }

                        texCorX = objImage.sprite.border.x + (texCorX - objImage.sprite.border.x) % (texRect.width - borderTotalWidth);
                        texCorY = objImage.sprite.border.y + (texCorY - objImage.sprite.border.y) % (texRect.height - borderTotalHeight);
                    }
                    else if (objImage.hasBorder)
                    {
                        // If objSize is below border size the border areas will shrink
                        texCorX *= Mathf.Clamp(borderTotalWidth / objSize.x, 1f, Mathf.Infinity);
                        texCorY *= Mathf.Clamp(borderTotalHeight / objSize.y, 1f, Mathf.Infinity);

                        if (texCorX > texRect.width - objImage.sprite.border.z && texCorX < objImage.sprite.border.x + fillRect.width)
                        {
                            texCorX = objImage.sprite.border.x + (texCorX - objImage.sprite.border.x) % (texRect.width - borderTotalWidth);
                        }
                        else if (texCorX > objImage.sprite.border.x + fillRect.width)
                        {
                            texCorX = texCorX - fillRect.width + texRect.width - borderTotalWidth;
                        }

                        if (texCorY > texRect.height - objImage.sprite.border.w && texCorY < objImage.sprite.border.y + fillRect.height)
                        {
                            texCorY = objImage.sprite.border.y + (texCorY - objImage.sprite.border.y) % (texRect.height - borderTotalHeight);
                        }
                        else if (texCorY > objImage.sprite.border.y + fillRect.height)
                        {
                            texCorY = texCorY - fillRect.height + texRect.height - borderTotalHeight;
                        }
                    }
                    else
                    {
                        if (texCorX > texRect.width)
                        {
                            texCorX %= texRect.width;
                        }
                        if (texCorY > texRect.height)
                        {
                            texCorY %= texRect.height;
                        }
                    }
                }
                // Correcting texture coordinates in case image is sliced
                else if (objImage.type == Image.Type.Sliced)
                {
                    if (isInsideFillRect)
                    {
                        if (!objImage.fillCenter)
                        {
                            toExclude.Add(result); continue;
                        }

                        texCorX = objImage.sprite.border.x + (texCorX - objImage.sprite.border.x) * ((texRect.width - borderTotalWidth) / fillRect.width);
                        texCorY = objImage.sprite.border.y + (texCorY - objImage.sprite.border.y) * ((texRect.height - borderTotalHeight) / fillRect.height);
                    }
                    else
                    {
                        // If objSize is below border size the border areas will shrink
                        texCorX *= Mathf.Clamp(borderTotalWidth / objSize.x, 1f, Mathf.Infinity);
                        texCorY *= Mathf.Clamp(borderTotalHeight / objSize.y, 1f, Mathf.Infinity);

                        if (texCorX > objImage.sprite.border.x && texCorX < objImage.sprite.border.x + fillRect.width)
                        {
                            texCorX = objImage.sprite.border.x + (texCorX - objImage.sprite.border.x) * ((texRect.width - borderTotalWidth) / fillRect.width);
                        }
                        else if (texCorX > objImage.sprite.border.x + fillRect.width)
                        {
                            texCorX = texCorX - fillRect.width + texRect.width - borderTotalWidth;
                        }

                        if (texCorY > objImage.sprite.border.y && texCorY < objImage.sprite.border.y + fillRect.height)
                        {
                            texCorY = objImage.sprite.border.y + (texCorY - objImage.sprite.border.y) * ((texRect.height - borderTotalHeight) / fillRect.height);
                        }
                        else if (texCorY > objImage.sprite.border.y + fillRect.height)
                        {
                            texCorY = texCorY - fillRect.height + texRect.height - borderTotalHeight;
                        }
                    }
                }
                #endregion
                // Correcting texture coordinates by scale in case simple or filled image
                else
                {
                    texCorX *= texRect.width / objSize.x;
                    texCorY *= texRect.height / objSize.y;
                }

                // For filled images, check if targeted spot is outside of the filled area
                #region FILLED
                if (objImage.type == Image.Type.Filled)
                {
                    var nCorX   = texRect.height > texRect.width ? texCorX * (texRect.height / texRect.width) : texCorX;
                    var nCorY   = texRect.width > texRect.height ? texCorY * (texRect.width / texRect.height) : texCorY;
                    var nWidth  = texRect.height > texRect.width ? texRect.height : texRect.width;
                    var nHeight = texRect.width > texRect.height ? texRect.width : texRect.height;

                    if (objImage.fillMethod == Image.FillMethod.Horizontal)
                    {
                        if (objImage.fillOrigin == (int)Image.OriginHorizontal.Left && texCorX / texRect.width > objImage.fillAmount)
                        {
                            toExclude.Add(result); continue;
                        }
                        if (objImage.fillOrigin == (int)Image.OriginHorizontal.Right && texCorX / texRect.width < (1 - objImage.fillAmount))
                        {
                            toExclude.Add(result); continue;
                        }
                    }

                    if (objImage.fillMethod == Image.FillMethod.Vertical)
                    {
                        if (objImage.fillOrigin == (int)Image.OriginVertical.Bottom && texCorY / texRect.height > objImage.fillAmount)
                        {
                            toExclude.Add(result); continue;
                        }
                        if (objImage.fillOrigin == (int)Image.OriginVertical.Top && texCorY / texRect.height < (1 - objImage.fillAmount))
                        {
                            toExclude.Add(result); continue;
                        }
                    }

                    #region RADIAL_90
                    if (objImage.fillMethod == Image.FillMethod.Radial90)
                    {
                        if (objImage.fillOrigin == (int)Image.Origin90.BottomLeft)
                        {
                            if (objImage.fillClockwise && Mathf.Atan(nCorY / nCorX) / (Mathf.PI / 2) < (1 - objImage.fillAmount))
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && Mathf.Atan(nCorY / nCorX) / (Mathf.PI / 2) > objImage.fillAmount)
                            {
                                toExclude.Add(result); continue;
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin90.TopLeft)
                        {
                            if (objImage.fillClockwise && nCorY < -(1 / Mathf.Tan((1 - objImage.fillAmount) * Mathf.PI / 2)) * nCorX + nHeight)
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && nCorY > -(1 / Mathf.Tan(objImage.fillAmount * Mathf.PI / 2)) * nCorX + nHeight)
                            {
                                toExclude.Add(result); continue;
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin90.TopRight)
                        {
                            if (objImage.fillClockwise && nCorY > Mathf.Tan((1 - objImage.fillAmount) * Mathf.PI / 2) * (nCorX - nWidth) + nHeight)
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && nCorY < Mathf.Tan(objImage.fillAmount * Mathf.PI / 2) * (nCorX - nWidth) + nHeight)
                            {
                                toExclude.Add(result); continue;
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin90.BottomRight)
                        {
                            if (objImage.fillClockwise && nCorY > (1 / Mathf.Tan((1 - objImage.fillAmount) * Mathf.PI / 2)) * (nWidth - nCorX))
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && nCorY < (1 / Mathf.Tan(objImage.fillAmount * Mathf.PI / 2)) * (nWidth - nCorX))
                            {
                                toExclude.Add(result); continue;
                            }
                        }
                    }
                    #endregion

                    #region RADIAL_180
                    if (objImage.fillMethod == Image.FillMethod.Radial180)
                    {
                        if (objImage.fillOrigin == (int)Image.Origin180.Bottom)
                        {
                            if (objImage.fillClockwise && Mathf.Atan2(nCorY, 2 * (nCorX - nWidth / 2)) < (1 - objImage.fillAmount) * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && Mathf.Atan2(texCorY, 2 * (nCorX - nWidth / 2)) > objImage.fillAmount * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin180.Left)
                        {
                            if (objImage.fillClockwise && Mathf.Atan2(nCorX, -2 * (nCorY - nHeight / 2)) < (1 - objImage.fillAmount) * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && Mathf.Atan2(nCorX, -2 * (nCorY - nHeight / 2)) > objImage.fillAmount * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin180.Top)
                        {
                            if (objImage.fillClockwise && Mathf.Atan2(nHeight - nCorY, -2 * (nCorX - nWidth / 2)) < (1 - objImage.fillAmount) * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && Mathf.Atan2(nHeight - nCorY, -2 * (nCorX - nWidth / 2)) > objImage.fillAmount * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin180.Right)
                        {
                            if (objImage.fillClockwise && Mathf.Atan2(nWidth - nCorX, 2 * (nCorY - nHeight / 2)) < (1 - objImage.fillAmount) * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                            if (!objImage.fillClockwise && Mathf.Atan2(nWidth - nCorX, 2 * (nCorY - nHeight / 2)) > objImage.fillAmount * Mathf.PI)
                            {
                                toExclude.Add(result); continue;
                            }
                        }
                    }
                    #endregion

                    #region RADIAL_360
                    if (objImage.fillMethod == Image.FillMethod.Radial360)
                    {
                        if (objImage.fillOrigin == (int)Image.Origin360.Bottom)
                        {
                            if (objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2) + Mathf.PI / 2;
                                var checkAngle = Mathf.PI * 2 * (1 - objImage.fillAmount);
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle < checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                            if (!objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2) + Mathf.PI / 2;
                                var checkAngle = Mathf.PI * 2 * objImage.fillAmount;
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle > checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin360.Right)
                        {
                            if (objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2);
                                var checkAngle = Mathf.PI * 2 * (1 - objImage.fillAmount);
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle < checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                            if (!objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2);
                                var checkAngle = Mathf.PI * 2 * objImage.fillAmount;
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle > checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin360.Top)
                        {
                            if (objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2) - Mathf.PI / 2;
                                var checkAngle = Mathf.PI * 2 * (1 - objImage.fillAmount);
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle < checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                            if (!objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2) - Mathf.PI / 2;
                                var checkAngle = Mathf.PI * 2 * objImage.fillAmount;
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle > checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                        }

                        if (objImage.fillOrigin == (int)Image.Origin360.Left)
                        {
                            if (objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2) - Mathf.PI;
                                var checkAngle = Mathf.PI * 2 * (1 - objImage.fillAmount);
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle < checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                            if (!objImage.fillClockwise)
                            {
                                var angle      = Mathf.Atan2(nCorY - nHeight / 2, nCorX - nWidth / 2) - Mathf.PI;
                                var checkAngle = Mathf.PI * 2 * objImage.fillAmount;
                                angle = angle < 0 ? Mathf.PI * 2 + angle : angle;
                                if (angle > checkAngle)
                                {
                                    toExclude.Add(result); continue;
                                }
                            }
                        }
                    }
                    #endregion
                }
                #endregion

                // Getting targeted pixel alpha from object's texture
                float alpha = objTex.GetPixel((int)(texCorX + texRect.x), (int)(texCorY + texRect.y)).a;

                // Deciding if we need to exclude the object from results list
                if (objAlphaCheck)
                {
                    if (objAlphaCheck.IncludeMaterialAlpha)
                    {
                        alpha *= objImage.color.a;
                    }
                    if (alpha < objAlphaCheck.AlphaThreshold)
                    {
                        toExclude.Add(result);
                    }
                }
                else
                {
                    if (IncludeMaterialAlpha)
                    {
                        alpha *= objImage.color.a;
                    }
                    if (alpha < AlphaThreshold)
                    {
                        toExclude.Add(result);
                    }
                }
            }
            catch (UnityException e)
            {
                if (Application.isEditor && ShowTextureWarnings)
                {
                    Debug.LogWarning(string.Format("Check for alpha failed: {0}", e.Message));
                }
            };
        }

        resultAppendList.RemoveAll(r => toExclude.Contains(r));
    }
Exemple #25
0
    /// <summary>
    /// 配置灯光环境
    /// </summary>
    void ConfigureLights()
    {
        mainLightExists = false;
        bool shadowmaskExists    = false;
        bool subtractiveLighting = false;

        shadowTileCount = 0;
        for (int i = 0; i < cull.visibleLights.Count; i++)
        {
            if (i == maxVisibleLights)  //超过最大灯光数量跳出循环
            {
                break;
            }
            VisibleLight light = cull.visibleLights[i];
            //visibleLightColors[i] = light.finalColor;
            Vector4 attenuation = Vector4.zero;
            attenuation.w = 1;
            Vector4 shadow = Vector4.zero;

            LightBakingOutput baking = light.light.bakingOutput;
            //标识
            visibleLightOcclusionMasks[i] = occlusionMasks[baking.occlusionMaskChannel + 1];
            if (baking.lightmapBakeType == LightmapBakeType.Mixed)
            {
                shadowmaskExists |= baking.mixedLightingMode == MixedLightingMode.Shadowmask;
                //subtractiveLighting |= baking.mixedLightingMode == MixedLightingMode.Subtractive;
                if (baking.mixedLightingMode == MixedLightingMode.Subtractive)
                {
                    subtractiveLighting = true;
                    //设置的颜色设置进去
                    cameraBuffer.SetGlobalColor(subtractiveShadowColorId, RenderSettings.subtractiveShadowColor);
                }
            }
            if (light.lightType == LightType.Directional)
            {
                Vector4 v = light.localToWorld.GetColumn(2);
                v.x = -v.x;
                v.y = -v.y;
                v.z = -v.z;
                visibleLightDirectionsOrPositions[i] = v;
                shadow   = ConfigureShadows(i, light.light);
                shadow.z = 1f;  //标识处理方向光
                if (i == 0 && shadow.x > 0f && shadowCascades > 0)
                {
                    mainLightExists  = true;
                    shadowTileCount -= 1;
                }
            }
            else
            {
                visibleLightDirectionsOrPositions[i] = light.localToWorld.GetColumn(3);  //获取点光源位置
                attenuation.x = 1f / Mathf.Max(light.range * light.range, 0.00001f);

                if (light.lightType == LightType.Spot)
                {
                    Vector4 v = light.localToWorld.GetColumn(2);
                    v.x = -v.x;
                    v.y = -v.y;
                    v.z = -v.z;
                    visibleLightSpotDirections[i] = v;
                    float outerRad   = Mathf.Deg2Rad * 0.5f * light.spotAngle;
                    float outerCos   = Mathf.Cos(outerRad);
                    float outerTan   = Mathf.Tan(outerRad);
                    float innerCos   = Mathf.Cos(Mathf.Atan(((64f - 18f) / 64f) * outerTan));
                    float angleRange = Mathf.Max(innerCos - outerCos, 0.001f);
                    attenuation.z = 1f / angleRange;
                    attenuation.w = -outerCos * attenuation.z;

                    //阴影
                    //Light shadowLight = light.light;
                    //Bounds shadowBounds;
                    //if (shadowLight.shadows != LightShadows.None && cull.GetShadowCasterBounds(i, out shadowBounds))
                    //{
                    //    shadowTileCount += 1;
                    //    shadow.x = shadowLight.shadowStrength;  //x分量存阴影强度
                    //    shadow.y = shadowLight.shadows == LightShadows.Soft ? 1f : 0f;
                    //}
                    shadow = ConfigureShadows(i, light.light);
                }
                else
                {
                    visibleLightSpotDirections[i] = Vector4.one;
                }
            }
            visibleLightColors[i]       = light.finalColor;
            visibleLightAttenuations[i] = attenuation;
            shadowData[i] = shadow;
        }
        bool useDistanceShadowmask = QualitySettings.shadowmaskMode == ShadowmaskMode.DistanceShadowmask;

        //是否存在shadowMask
        CoreUtils.SetKeyword(cameraBuffer, shadowmaskKeyword, shadowmaskExists && !useDistanceShadowmask);
        CoreUtils.SetKeyword(cameraBuffer, subtractiveLightingKeyword, subtractiveLighting);
        CoreUtils.SetKeyword(cameraBuffer, distanceShadowmask, shadowmaskExists && useDistanceShadowmask);
        //for (; i < maxVisibleLights; i++)   //还原清除后面灯光颜色(0,0,0,0)
        //{
        //    visibleLightColors[i] = Color.clear;
        //}
        //告诉Unity 超出最大灯光数量的索引设置为-1使其不起作用
        if (mainLightExists || cull.visibleLights.Count > maxVisibleLights)
        {
            int[] lightIndices = cull.GetLightIndexMap();
            if (mainLightExists)
            {
                lightIndices[0] = -1;
            }
            for (int i = maxVisibleLights; i < cull.visibleLights.Count; i++)
            {
                lightIndices[i] = -1;
            }
            cull.SetLightIndexMap(lightIndices);
        }
    }
Exemple #26
0
    void Update()
    {
        index          = FindClosestEnemy();
        attackTimer   += Time.deltaTime;
        beamTimer     += Time.deltaTime;
        lifeSpanTimer += Time.deltaTime;

        if (index != -1)
        {
            if (attackTimer > 1f)
            {
                if (enemies[index].transform.position.y < 2.35f)
                {
                    aimedEnemy = enemies[index];

                    //shoot
                    Vector3 diff = enemies[index].transform.position - new Vector3(-0.1875f, -1.6275f);

                    float rotation = 0f;
                    //rotation
                    if (diff.x == 0f)
                    {
                        if (diff.y <= 0f)
                        {
                            rotation = 0f;
                        }
                        if (diff.y > 0f)
                        {
                            rotation = 180f;
                        }
                    }
                    if (diff.x < 0f)
                    {
                        if (diff.y < 0f)
                        {
                            rotation = -Mathf.Atan(diff.x / diff.y) * 180 / Mathf.PI + 180f;
                        }
                        if (diff.y == 0f)
                        {
                            rotation = 0f;
                        }
                        if (diff.y > 0f)
                        {
                            rotation = -Mathf.Atan(diff.x / diff.y) * 180 / Mathf.PI;
                        }
                    }

                    if (diff.x > 0f)
                    {
                        if (diff.y < 0f)
                        {
                            rotation = -Mathf.Atan(diff.x / diff.y) * 180 / Mathf.PI + 180f;
                        }
                        if (diff.y == 0f)
                        {
                            rotation = 0f;
                        }
                        if (diff.y > 0f)
                        {
                            rotation = -Mathf.Atan(diff.x / diff.y) * 180 / Mathf.PI;
                        }
                    }
                    Quaternion rot = Quaternion.Euler(0f, 0f, rotation);
                    beamImage.transform.rotation = rot;

                    //length
                    beamLength = Mathf.Sqrt(diff.x * diff.x + diff.y * diff.y * (((Screen.height / (float)Screen.width) > 2) ? 1.25f * 1.25f : 1)) * 1.4f;

                    beamFired = true;
                    beamTimer = 0f;

                    attackTimer = 0f;
                }
            }
        }

        if (beamFired)
        {
            if (beamTimer >= 0.5f)
            {
                beamImage.transform.localScale = new Vector3(1f, 0f);
                beamFired = false;
                if (aimedEnemy != null)
                {
                    aimedEnemy.gameObject.GetComponent <DamageDealer>().DealDamage(Mathf.RoundToInt(dmg * Random.Range(0.8f, 1.2f)));
                }
            }
            else
            {
                float length = beamLength * beamTimer * 2f;
                beamImage.transform.localScale = new Vector3(1f, length);
            }
        }

        if (lifeSpanTimer > 20.9f)
        {
            Destroy(gameObject);
        }
    }
Exemple #27
0
 public static float FocaltoFOV(float focal, float axisResolution)
 {
     return(2.0f * Mathf.Atan(0.5f * axisResolution / focal) * Mathf.Rad2Deg); // virtual camera (pinhole type) vertical field of view
 }
Exemple #28
0
    private Vector3 getVelocityDirection(int i)
    {
        float angle = Mathf.Atan(TerrainManager.instance.multiplier_y * (parsing.yData[i + 1] - parsing.yData[i]) / (parsing.xData[i + 1] - parsing.xData[i]));

        return(new Vector3(Mathf.Cos(angle), Mathf.Sin(angle), 0));
    }
Exemple #29
0
        void InitializeLightConstants(List <VisibleLight> lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightDistanceAttenuation, out Vector4 lightSpotDir,
                                      out Vector4 lightSpotAttenuation)
        {
            lightPos   = k_DefaultLightPosition;
            lightColor = k_DefaultLightColor;
            lightDistanceAttenuation = k_DefaultLightSpotAttenuation;
            lightSpotDir             = k_DefaultLightSpotDirection;
            lightSpotAttenuation     = k_DefaultLightAttenuation;

            // When no lights are visible, main light will be set to -1.
            // In this case we initialize it to default values and return
            if (lightIndex < 0)
            {
                return;
            }

            VisibleLight lightData = lights[lightIndex];

            if (lightData.lightType == LightType.Directional)
            {
                Vector4 dir = -lightData.localToWorld.GetColumn(2);
                lightPos = new Vector4(dir.x, dir.y, dir.z, 0.0f);
            }
            else
            {
                Vector4 pos = lightData.localToWorld.GetColumn(3);
                lightPos = new Vector4(pos.x, pos.y, pos.z, 1.0f);
            }

            // VisibleLight.finalColor already returns color in active color space
            lightColor = lightData.finalColor;

            // Directional Light attenuation is initialize so distance attenuation always be 1.0
            if (lightData.lightType != LightType.Directional)
            {
                // Light attenuation in lightweight matches the unity vanilla one.
                // attenuation = 1.0 / 1.0 + distanceToLightSqr * quadraticAttenuation
                // then a smooth factor is applied to linearly fade attenuation to light range
                // the attenuation smooth factor starts having effect at 80% of light range
                // smoothFactor = (lightRangeSqr - distanceToLightSqr) / (lightRangeSqr - fadeStartDistanceSqr)
                // We rewrite smoothFactor to be able to pre compute the constant terms below and apply the smooth factor
                // with one MAD instruction
                // smoothFactor =  distanceSqr * (1.0 / (fadeDistanceSqr - lightRangeSqr)) + (-lightRangeSqr / (fadeDistanceSqr - lightRangeSqr)
                //                 distanceSqr *           oneOverFadeRangeSqr             +              lightRangeSqrOverFadeRangeSqr
                float lightRangeSqr                 = lightData.range * lightData.range;
                float fadeStartDistanceSqr          = 0.8f * 0.8f * lightRangeSqr;
                float fadeRangeSqr                  = (fadeStartDistanceSqr - lightRangeSqr);
                float oneOverFadeRangeSqr           = 1.0f / fadeRangeSqr;
                float lightRangeSqrOverFadeRangeSqr = -lightRangeSqr / fadeRangeSqr;
                float quadAtten = 25.0f / lightRangeSqr;
                lightDistanceAttenuation = new Vector4(quadAtten, oneOverFadeRangeSqr, lightRangeSqrOverFadeRangeSqr, 1.0f);
            }

            if (lightData.lightType == LightType.Spot)
            {
                Vector4 dir = lightData.localToWorld.GetColumn(2);
                lightSpotDir = new Vector4(-dir.x, -dir.y, -dir.z, 0.0f);

                // Spot Attenuation with a linear falloff can be defined as
                // (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)
                // This can be rewritten as
                // invAngleRange = 1.0 / (cosInnerAngle - cosOuterAngle)
                // SdotL * invAngleRange + (-cosOuterAngle * invAngleRange)
                // If we precompute the terms in a MAD instruction
                float cosOuterAngle = Mathf.Cos(Mathf.Deg2Rad * lightData.spotAngle * 0.5f);
                // We neeed to do a null check for particle lights
                // This should be changed in the future
                // Particle lights will use an inline function
                float cosInnerAngle;
                if (lightData.light != null)
                {
                    cosInnerAngle = Mathf.Cos(LightmapperUtils.ExtractInnerCone(lightData.light) * 0.5f);
                }
                else
                {
                    cosInnerAngle = Mathf.Cos((2.0f * Mathf.Atan(Mathf.Tan(lightData.spotAngle * 0.5f * Mathf.Deg2Rad) * (64.0f - 18.0f) / 64.0f)) * 0.5f);
                }
                float smoothAngleRange = Mathf.Max(0.001f, cosInnerAngle - cosOuterAngle);
                float invAngleRange    = 1.0f / smoothAngleRange;
                float add = -cosOuterAngle * invAngleRange;
                lightSpotAttenuation = new Vector4(invAngleRange, add, 0.0f);
            }

            Light light = lightData.light;

            // TODO: Add support to shadow mask
            if (light != null && light.bakingOutput.mixedLightingMode == MixedLightingMode.Subtractive && light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed)
            {
                if (m_MixedLightingSetup == MixedLightingSetup.None && lightData.light.shadows != LightShadows.None)
                {
                    m_MixedLightingSetup       = MixedLightingSetup.Subtractive;
                    lightDistanceAttenuation.w = 0.0f;
                }
            }
        }
    private void PlaceCubeNear(Vector3 clickPoint)
    {
        if (camScript.editing == true && OverUI == false)
        {
            var finalPosition = grid.GetNearestPointOnGrid(clickPoint);
            if (clickNum == 1)
            {
                startPos = finalPosition;
                if (history.Count > 0)
                {
                    JointCheck(startPos);
                }
                if (overlap == false && midCreate == false)
                {
                    history.Add(startPos);
                    cubeClickBack = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
                    cubeClickBack.transform.position = new Vector3(-2.7f, finalPosition.y, finalPosition.z);
                    cubeClickBack.transform.Rotate(0, 0, 90);
                    cubeClickBack.transform.localScale = new Vector3(cubeClickScale, cubeClickScaleY, cubeClickScale);
                    cubeClickBack.GetComponent <Renderer>().material.color = Color.green;
                    cubeClickBack.AddComponent(typeof(CustomStructureConfig));
                    cubeClickBack.tag  = "Structure";
                    cubeClickBack.name = "Pivot";
                    GroundCheck(startPos, cubeClickBack);

                    cubeClickFront = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
                    cubeClickFront.transform.position = new Vector3(2.7f, finalPosition.y, finalPosition.z);
                    cubeClickFront.transform.Rotate(0, 0, 90);
                    cubeClickFront.transform.localScale = new Vector3(cubeClickScale, cubeClickScaleY, cubeClickScale);
                    cubeClickFront.GetComponent <Renderer>().material.color = Color.green;
                    cubeClickFront.AddComponent(typeof(CustomStructureConfig));
                    cubeClickFront.tag  = "Structure";
                    cubeClickFront.name = "Pivot";
                    GroundCheck(startPos, cubeClickFront);
                    clickNum = 2;
                }
            }
            else if (clickNum == 2)
            {
                endPos = finalPosition;
                if (history.Count > 0)
                {
                    JointCheck(endPos);
                }
                if (endPos != history[history.Count - 1])
                {
                    history.Add(endPos);
                    if (overlap == false)
                    {
                        cubeClickBack = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
                        cubeClickBack.transform.position = new Vector3(-2.7f, finalPosition.y, finalPosition.z);
                        cubeClickBack.transform.Rotate(0, 0, 90);
                        cubeClickBack.transform.localScale = new Vector3(cubeClickScale, cubeClickScaleY, cubeClickScale);
                        cubeClickBack.GetComponent <Renderer>().material.color = Color.blue;
                        cubeClickBack.AddComponent(typeof(CustomStructureConfig));
                        cubeClickBack.tag  = "Structure";
                        cubeClickBack.name = "Pivot";
                        GroundCheck(endPos, cubeClickBack);

                        cubeClickFront = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
                        cubeClickFront.transform.position = new Vector3(2.7f, finalPosition.y, finalPosition.z);
                        cubeClickFront.transform.Rotate(0, 0, 90);
                        cubeClickFront.transform.localScale = new Vector3(cubeClickScale, cubeClickScaleY, cubeClickScale);
                        cubeClickFront.GetComponent <Renderer>().material.color = Color.blue;
                        cubeClickFront.AddComponent(typeof(CustomStructureConfig));
                        cubeClickFront.tag  = "Structure";
                        cubeClickFront.name = "Pivot";
                        GroundCheck(endPos, cubeClickFront);
                    }
                    Vector3 mid     = startPos + (endPos - startPos) / 2;
                    float   changeY = endPos.y - startPos.y;
                    float   changeZ = endPos.z - startPos.z;
                    float   difYZ   = changeY / changeZ;
                    float   angle   = Mathf.Atan(difYZ);
                    double  result  = RadianToDegree(angle);

                    float xScale  = Mathf.Abs(endPos.x - startPos.x);
                    float yScale  = Mathf.Abs(endPos.y - startPos.y);
                    float zScale  = Mathf.Abs(endPos.z - startPos.z);
                    float zScale2 = Mathf.Abs((zScale * zScale) + (yScale * yScale));
                    float root    = Mathf.Sqrt(zScale2);

                    if (xScale == 0)
                    {
                        xScale = 1;
                    }
                    if (yScale == 0)
                    {
                        yScale = 1;
                    }
                    if (zScale == 0)
                    {
                        zScale = yScale;
                    }

                    if (materialDrop.value == 0) //steel
                    {
                        poleBack = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        GameObject go = poleBack;

                        go.name = "steelBack";
                        go.transform.position   = new Vector3(-2.7f, mid.y, mid.z);
                        go.transform.localScale = new Vector3(0.5f, 0.5f, root + 0.5f);
                        go.transform.Rotate(new Vector3(-(float)result, 0, 0));
                        go.tag = "Structure";
                        go.AddComponent(typeof(Rigidbody));
                        go.AddComponent(typeof(CustomStructureConfig));
                        Rigidbody rb = go.GetComponent <Rigidbody>();
                        rb.isKinematic = true;
                        FindNearPivots(go.transform.position, go.transform.localScale, go);

                        poleFront = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        go        = poleFront; //(GameObject go = blahblablah)

                        go.name = "steelFront";
                        go.transform.position   = new Vector3(2.7f, mid.y, mid.z);
                        go.transform.localScale = new Vector3(0.5f, 0.5f, root + 0.5f);
                        go.transform.Rotate(new Vector3(-(float)result, 0, 0));
                        go.tag = "Structure";
                        go.AddComponent(typeof(Rigidbody));
                        go.AddComponent(typeof(CustomStructureConfig));
                        rb             = go.GetComponent <Rigidbody>();
                        rb.isKinematic = true;
                        FindNearPivots(go.transform.position, go.transform.localScale, go);
                    }
                    else if (materialDrop.value == 1) //road
                    {
                        roadCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                        GameObject go = roadCube;

                        go.name = "Road";
                        go.transform.position   = new Vector3(0, mid.y, mid.z);
                        go.transform.localScale = new Vector3(5.4f, 0.5f, root + 0.5f);
                        go.transform.Rotate(new Vector3(-(float)result, 0, 0));
                        go.GetComponent <Renderer>().material.color = Color.black;
                        go.tag = "Structure";
                        go.AddComponent(typeof(Rigidbody));
                        go.AddComponent(typeof(CustomStructureConfig));
                        Rigidbody rb = go.GetComponent <Rigidbody>();
                        rb.isKinematic = true;
                        FindNearPivots(go.transform.position, go.transform.localScale, go);
                    }
                    clickNum = 1;
                }
                else
                {
                    clickNum = 1;
                }
            }
            //Destroy(cubeClickBack);
        }
    }