<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DragMethod_RotateDiagram.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-03 13:40:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "DragMethod_RotateDiagram.hxx"

#include "SelectionHelper.hxx"
#include "CommonConverters.hxx"
#include "ChartModelHelper.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "ChartTypeHelper.hxx"
#include "ThreeDHelper.hxx"

#ifndef _SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX
#include <svx/sdr/overlay/overlaypolypolygon.hxx>
#endif
#ifndef _SDR_OVERLAY_OVERLAYMANAGER_HXX
#include <svx/sdr/overlay/overlaymanager.hxx>
#endif

// header for class E3dScene
#ifndef _E3D_SCENE3D_HXX
#include <svx/scene3d.hxx>
#endif

#ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX
#include <basegfx/matrix/b3dhommatrix.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#define FIXED_SIZE_FOR_3D_CHART_VOLUME (10000.0)

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;

DragMethod_RotateDiagram::DragMethod_RotateDiagram( DrawViewWrapper& rDrawViewWrapper
        , const rtl::OUString& rObjectCID
        , const Reference< frame::XModel >& xChartModel
        , RotationDirection eRotationDirection )
    : DragMethod_Base( rDrawViewWrapper, rObjectCID, xChartModel, ActionDescriptionProvider::ROTATE )
    , m_pScene(0)
    , m_aReferenceRect(100,100,100,100)
    , m_aStartPos(0,0)
    , m_aWireframePoly()
    , m_fInitialXAngleRad(0.0)
    , m_fInitialYAngleRad(0.0)
    , m_fInitialZAngleRad(0.0)
    , m_fAdditionalXAngleRad(0.0)
    , m_fAdditionalYAngleRad(0.0)
    , m_fAdditionalZAngleRad(0.0)
    , m_eRotationDirection(eRotationDirection)
    , m_bRightAngledAxes(sal_False)
{
    m_pScene = SelectionHelper::getSceneToRotate( rDrawViewWrapper.getNamedSdrObject( rObjectCID ) );
    SdrObject* pObj = rDrawViewWrapper.getSelectedObject();
    if(pObj && m_pScene)
    {
        m_aReferenceRect = pObj->GetLogicRect();
        Rectangle aTemp = m_pScene->GetLogicRect();

        m_pScene->CreateWireframe(m_aWireframePoly, NULL );

        uno::Reference< chart2::XDiagram > xDiagram( ChartModelHelper::findDiagram(this->getChartModel()) );
        uno::Reference< beans::XPropertySet > xDiagramProperties( xDiagram, uno::UNO_QUERY );
        if( xDiagramProperties.is() )
        {
            ThreeDHelper::getRotationAngleFromDiagram( xDiagramProperties
                , m_fInitialXAngleRad, m_fInitialYAngleRad, m_fInitialZAngleRad );
            if( ChartTypeHelper::isSupportingRightAngledAxes(
                DiagramHelper::getChartTypeByIndex( xDiagram, 0 ) ) )
                xDiagramProperties->getPropertyValue(C2U( "RightAngledAxes" )) >>= m_bRightAngledAxes;
            if(m_bRightAngledAxes)
            {
                if( m_eRotationDirection==ROTATIONDIRECTION_Z )
                    m_eRotationDirection=ROTATIONDIRECTION_FREE;
                ThreeDHelper::adaptRadAnglesForRightAngledAxes( m_fInitialXAngleRad, m_fInitialYAngleRad );
            }
        }
    }
}
DragMethod_RotateDiagram::~DragMethod_RotateDiagram()
{
}
void DragMethod_RotateDiagram::TakeComment(String& /*rStr*/) const
{
}
FASTBOOL DragMethod_RotateDiagram::Beg()
{
    m_aStartPos = DragStat().GetStart();
    SetDragPolys();
    Show();
    return true;
}
void DragMethod_RotateDiagram::Mov(const Point& rPnt)
{
    if( DragStat().CheckMinMoved(rPnt) )
    {
        Hide();

        //calculate new angle
        double fX = F_PI / 2.0 * (double)(rPnt.Y() - m_aStartPos.Y())
                / (double)m_aReferenceRect.GetHeight();
        double fY = F_PI * (double)(rPnt.X() - m_aStartPos.X())
                / (double)m_aReferenceRect.GetWidth();

        if( m_eRotationDirection != ROTATIONDIRECTION_Y )
            m_fAdditionalYAngleRad = fY;
        else
            m_fAdditionalYAngleRad = 0.0;
        if( m_eRotationDirection != ROTATIONDIRECTION_X )
            m_fAdditionalXAngleRad = fX;
        else
            m_fAdditionalXAngleRad = 0.0;
        m_fAdditionalZAngleRad = 0.0;

        if( m_eRotationDirection == ROTATIONDIRECTION_Z )
        {
            m_fAdditionalXAngleRad = 0.0;
            m_fAdditionalYAngleRad = 0.0;

            double fCx = m_aReferenceRect.Center().X();
            double fCy = m_aReferenceRect.Center().Y();

            m_fAdditionalZAngleRad = atan((double)(fCx - m_aStartPos.X())/(m_aStartPos.Y()-fCy))
                + atan((double)(fCx - rPnt.X())/(fCy-rPnt.Y()));
        }

        DragStat().NextMove(rPnt);
        MovAllPoints();

        Show();
    }
}
void DragMethod_RotateDiagram::CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList)
{
    ::basegfx::B3DHomMatrix aCurrentTransform;
    aCurrentTransform.translate( -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0 );

    double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
    double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
    double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

    if(!m_bRightAngledAxes)
        aCurrentTransform.rotate( fResultX, fResultY, fResultZ );
    else
    {
        ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );
        aCurrentTransform.shearXY(fResultY,-(fResultX));
    }

    const sal_uInt32 nPntCnt(m_aWireframePoly.count());
     if(nPntCnt > 1L && m_pScene)
    {
        B3dCamera& rCameraSet = m_pScene->GetCameraSet();
        for(sal_uInt32 b(0L); b < nPntCnt; b += 2L)
        {
            ::basegfx::B2DPolygon aLine;
            ::basegfx::B3DPoint aPnt1(aCurrentTransform * m_aWireframePoly.getB3DPoint(b));
            aPnt1 = rCameraSet.WorldToViewCoor(aPnt1);
            aLine.append(::basegfx::B2DPoint(aPnt1.getX(), aPnt1.getY()));

            ::basegfx::B3DPoint aPnt2(aCurrentTransform * m_aWireframePoly.getB3DPoint(b + 1L));
            aPnt2 = rCameraSet.WorldToViewCoor(aPnt2);
            aLine.append(::basegfx::B2DPoint(aPnt2.getX(), aPnt2.getY()));

            basegfx::B2DPolyPolygon aResult(aLine);
            ::sdr::overlay::OverlayPolyPolygonStriped* pNew = new ::sdr::overlay::OverlayPolyPolygonStriped(aResult);
            rOverlayManager.add(*pNew);
            rOverlayList.append(*pNew);
        }
    }
}

FASTBOOL DragMethod_RotateDiagram::End(FASTBOOL bCopy)
{
    Hide();

    double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
    double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
    double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

    if(m_bRightAngledAxes)
        ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );

    ThreeDHelper::setRotationAngleToDiagram( uno::Reference< beans::XPropertySet >( ChartModelHelper::findDiagram( this->getChartModel() ), uno::UNO_QUERY )
        , fResultX, fResultY, fResultZ );

    return true;
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS chart07 (1.3.4); FILE MERGED 2007/07/10 13:38:14 bm 1.3.4.1: #i69281# warnings removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DragMethod_RotateDiagram.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-25 08:45:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "DragMethod_RotateDiagram.hxx"

#include "SelectionHelper.hxx"
#include "CommonConverters.hxx"
#include "ChartModelHelper.hxx"
#include "macros.hxx"
#include "DiagramHelper.hxx"
#include "ChartTypeHelper.hxx"
#include "ThreeDHelper.hxx"

#ifndef _SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX
#include <svx/sdr/overlay/overlaypolypolygon.hxx>
#endif
#ifndef _SDR_OVERLAY_OVERLAYMANAGER_HXX
#include <svx/sdr/overlay/overlaymanager.hxx>
#endif

// header for class E3dScene
#ifndef _E3D_SCENE3D_HXX
#include <svx/scene3d.hxx>
#endif

#ifndef _BGFX_MATRIX_B3DHOMMATRIX_HXX
#include <basegfx/matrix/b3dhommatrix.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#define FIXED_SIZE_FOR_3D_CHART_VOLUME (10000.0)

//.............................................................................
namespace chart
{
//.............................................................................

using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;

DragMethod_RotateDiagram::DragMethod_RotateDiagram( DrawViewWrapper& rDrawViewWrapper
        , const rtl::OUString& rObjectCID
        , const Reference< frame::XModel >& xChartModel
        , RotationDirection eRotationDirection )
    : DragMethod_Base( rDrawViewWrapper, rObjectCID, xChartModel, ActionDescriptionProvider::ROTATE )
    , m_pScene(0)
    , m_aReferenceRect(100,100,100,100)
    , m_aStartPos(0,0)
    , m_aWireframePoly()
    , m_fInitialXAngleRad(0.0)
    , m_fInitialYAngleRad(0.0)
    , m_fInitialZAngleRad(0.0)
    , m_fAdditionalXAngleRad(0.0)
    , m_fAdditionalYAngleRad(0.0)
    , m_fAdditionalZAngleRad(0.0)
    , m_eRotationDirection(eRotationDirection)
    , m_bRightAngledAxes(sal_False)
{
    m_pScene = SelectionHelper::getSceneToRotate( rDrawViewWrapper.getNamedSdrObject( rObjectCID ) );
    SdrObject* pObj = rDrawViewWrapper.getSelectedObject();
    if(pObj && m_pScene)
    {
        m_aReferenceRect = pObj->GetLogicRect();
        Rectangle aTemp = m_pScene->GetLogicRect();

        m_pScene->CreateWireframe(m_aWireframePoly, NULL );

        uno::Reference< chart2::XDiagram > xDiagram( ChartModelHelper::findDiagram(this->getChartModel()) );
        uno::Reference< beans::XPropertySet > xDiagramProperties( xDiagram, uno::UNO_QUERY );
        if( xDiagramProperties.is() )
        {
            ThreeDHelper::getRotationAngleFromDiagram( xDiagramProperties
                , m_fInitialXAngleRad, m_fInitialYAngleRad, m_fInitialZAngleRad );
            if( ChartTypeHelper::isSupportingRightAngledAxes(
                DiagramHelper::getChartTypeByIndex( xDiagram, 0 ) ) )
                xDiagramProperties->getPropertyValue(C2U( "RightAngledAxes" )) >>= m_bRightAngledAxes;
            if(m_bRightAngledAxes)
            {
                if( m_eRotationDirection==ROTATIONDIRECTION_Z )
                    m_eRotationDirection=ROTATIONDIRECTION_FREE;
                ThreeDHelper::adaptRadAnglesForRightAngledAxes( m_fInitialXAngleRad, m_fInitialYAngleRad );
            }
        }
    }
}
DragMethod_RotateDiagram::~DragMethod_RotateDiagram()
{
}
void DragMethod_RotateDiagram::TakeComment(String& /*rStr*/) const
{
}
FASTBOOL DragMethod_RotateDiagram::Beg()
{
    m_aStartPos = DragStat().GetStart();
    SetDragPolys();
    Show();
    return true;
}
void DragMethod_RotateDiagram::Mov(const Point& rPnt)
{
    if( DragStat().CheckMinMoved(rPnt) )
    {
        Hide();

        //calculate new angle
        double fX = F_PI / 2.0 * (double)(rPnt.Y() - m_aStartPos.Y())
                / (double)m_aReferenceRect.GetHeight();
        double fY = F_PI * (double)(rPnt.X() - m_aStartPos.X())
                / (double)m_aReferenceRect.GetWidth();

        if( m_eRotationDirection != ROTATIONDIRECTION_Y )
            m_fAdditionalYAngleRad = fY;
        else
            m_fAdditionalYAngleRad = 0.0;
        if( m_eRotationDirection != ROTATIONDIRECTION_X )
            m_fAdditionalXAngleRad = fX;
        else
            m_fAdditionalXAngleRad = 0.0;
        m_fAdditionalZAngleRad = 0.0;

        if( m_eRotationDirection == ROTATIONDIRECTION_Z )
        {
            m_fAdditionalXAngleRad = 0.0;
            m_fAdditionalYAngleRad = 0.0;

            double fCx = m_aReferenceRect.Center().X();
            double fCy = m_aReferenceRect.Center().Y();

            m_fAdditionalZAngleRad = atan((double)(fCx - m_aStartPos.X())/(m_aStartPos.Y()-fCy))
                + atan((double)(fCx - rPnt.X())/(fCy-rPnt.Y()));
        }

        DragStat().NextMove(rPnt);
        MovAllPoints();

        Show();
    }
}
void DragMethod_RotateDiagram::CreateOverlayGeometry(::sdr::overlay::OverlayManager& rOverlayManager, ::sdr::overlay::OverlayObjectList& rOverlayList)
{
    ::basegfx::B3DHomMatrix aCurrentTransform;
    aCurrentTransform.translate( -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0,
                                 -FIXED_SIZE_FOR_3D_CHART_VOLUME/2.0 );

    double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
    double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
    double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

    if(!m_bRightAngledAxes)
        aCurrentTransform.rotate( fResultX, fResultY, fResultZ );
    else
    {
        ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );
        aCurrentTransform.shearXY(fResultY,-(fResultX));
    }

    const sal_uInt32 nPntCnt(m_aWireframePoly.count());
     if(nPntCnt > 1L && m_pScene)
    {
        B3dCamera& rCameraSet = m_pScene->GetCameraSet();
        for(sal_uInt32 b(0L); b < nPntCnt; b += 2L)
        {
            ::basegfx::B2DPolygon aLine;
            ::basegfx::B3DPoint aPnt1(aCurrentTransform * m_aWireframePoly.getB3DPoint(b));
            aPnt1 = rCameraSet.WorldToViewCoor(aPnt1);
            aLine.append(::basegfx::B2DPoint(aPnt1.getX(), aPnt1.getY()));

            ::basegfx::B3DPoint aPnt2(aCurrentTransform * m_aWireframePoly.getB3DPoint(b + 1L));
            aPnt2 = rCameraSet.WorldToViewCoor(aPnt2);
            aLine.append(::basegfx::B2DPoint(aPnt2.getX(), aPnt2.getY()));

            basegfx::B2DPolyPolygon aResult(aLine);
            ::sdr::overlay::OverlayPolyPolygonStriped* pNew = new ::sdr::overlay::OverlayPolyPolygonStriped(aResult);
            rOverlayManager.add(*pNew);
            rOverlayList.append(*pNew);
        }
    }
}

FASTBOOL DragMethod_RotateDiagram::End(FASTBOOL /* bCopy */)
{
    Hide();

    double fResultX = m_fInitialXAngleRad + m_fAdditionalXAngleRad;
    double fResultY = m_fInitialYAngleRad + m_fAdditionalYAngleRad;
    double fResultZ = m_fInitialZAngleRad + m_fAdditionalZAngleRad;

    if(m_bRightAngledAxes)
        ThreeDHelper::adaptRadAnglesForRightAngledAxes( fResultX, fResultY );

    ThreeDHelper::setRotationAngleToDiagram( uno::Reference< beans::XPropertySet >( ChartModelHelper::findDiagram( this->getChartModel() ), uno::UNO_QUERY )
        , fResultX, fResultY, fResultZ );

    return true;
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/http_pipelining_compatibility_client.h"

#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/stringprintf.h"
#include "chrome/browser/io_thread.h"
#include "chrome/common/chrome_version_info.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/load_flags.h"
#include "net/base/network_change_notifier.h"
#include "net/disk_cache/histogram_macros.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_network_session.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_version.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/url_request_context_getter.h"

namespace chrome_browser_net {

HttpPipeliningCompatibilityClient::HttpPipeliningCompatibilityClient()
    : num_finished_(0),
      num_succeeded_(0) {
}

HttpPipeliningCompatibilityClient::~HttpPipeliningCompatibilityClient() {
}

void HttpPipeliningCompatibilityClient::Start(
    const std::string& base_url,
    std::vector<RequestInfo>& requests,
    bool collect_server_stats,
    const net::CompletionCallback& callback,
    net::URLRequestContext* url_request_context) {
  net::HttpNetworkSession* old_session =
      url_request_context->http_transaction_factory()->GetSession();
  net::HttpNetworkSession::Params params = old_session->params();
  params.force_http_pipelining = true;
  scoped_refptr<net::HttpNetworkSession> session =
      new net::HttpNetworkSession(params);
  http_transaction_factory_.reset(
      net::HttpNetworkLayer::CreateFactory(session.get()));

  url_request_context_ = new net::URLRequestContext;
  url_request_context_->CopyFrom(url_request_context);
  url_request_context_->set_http_transaction_factory(
      http_transaction_factory_.get());

  finished_callback_ = callback;
  for (size_t i = 0; i < requests.size(); ++i) {
    requests_.push_back(new Request(i, base_url, requests[i], this,
                                    url_request_context_.get()));
  }
  if (collect_server_stats) {
    RequestInfo info;
    info.filename = "stats.txt";
    // This is just to determine the expected length of the response.
    // StatsRequest doesn't expect this exact value, but it does expect this
    // exact length.
    info.expected_response =
        "were_all_requests_http_1_1:1,max_pipeline_depth:5";
    requests_.push_back(new StatsRequest(requests.size(), base_url, info, this,
                                         url_request_context_.get()));
  }
}

void HttpPipeliningCompatibilityClient::OnRequestFinished(int request_id,
                                                          Status status) {
  // The CACHE_HISTOGRAM_* macros are used, because they allow dynamic metric
  // names.
  CACHE_HISTOGRAM_ENUMERATION(GetMetricName(request_id, "Status"),
                              status, STATUS_MAX);
  ++num_finished_;
  if (status == SUCCESS) {
    ++num_succeeded_;
  }
  if (num_finished_ == requests_.size()) {
    UMA_HISTOGRAM_BOOLEAN("NetConnectivity.Pipeline.Success",
                          num_succeeded_ == requests_.size());
    finished_callback_.Run(0);
  }
}

void HttpPipeliningCompatibilityClient::ReportNetworkError(int request_id,
                                                           int error_code) {
  CACHE_HISTOGRAM_ENUMERATION(GetMetricName(request_id, "NetworkError"),
                              -error_code, 900);
}

void HttpPipeliningCompatibilityClient::ReportResponseCode(int request_id,
                                                           int response_code) {
  CACHE_HISTOGRAM_ENUMERATION(GetMetricName(request_id, "ResponseCode"),
                              response_code, 600);
}

std::string HttpPipeliningCompatibilityClient::GetMetricName(
    int request_id, const char* description) {
  return base::StringPrintf("NetConnectivity.Pipeline.%d.%s",
                            request_id, description);
}

HttpPipeliningCompatibilityClient::Request::Request(
    int request_id,
    const std::string& base_url,
    const RequestInfo& info,
    HttpPipeliningCompatibilityClient* client,
    net::URLRequestContext* url_request_context)
    : request_id_(request_id),
      request_(new net::URLRequest(GURL(base_url + info.filename), this)),
      info_(info),
      client_(client) {
  request_->set_context(url_request_context);
  request_->set_load_flags(net::LOAD_BYPASS_CACHE |
                           net::LOAD_DISABLE_CACHE |
                           net::LOAD_DO_NOT_SAVE_COOKIES |
                           net::LOAD_DO_NOT_SEND_COOKIES |
                           net::LOAD_DO_NOT_PROMPT_FOR_LOGIN |
                           net::LOAD_DO_NOT_SEND_AUTH_DATA);
  request_->Start();
}

HttpPipeliningCompatibilityClient::Request::~Request() {
}

void HttpPipeliningCompatibilityClient::Request::OnReceivedRedirect(
    net::URLRequest* request,
    const GURL& new_url,
    bool* defer_redirect) {
  *defer_redirect = true;
  request->Cancel();
  Finished(REDIRECTED);
}

void HttpPipeliningCompatibilityClient::Request::OnSSLCertificateError(
    net::URLRequest* request,
    const net::SSLInfo& ssl_info,
    bool fatal) {
  Finished(CERT_ERROR);
}

void HttpPipeliningCompatibilityClient::Request::OnResponseStarted(
    net::URLRequest* request) {
  int response_code = request->GetResponseCode();
  if (response_code > 0) {
    client_->ReportResponseCode(request_id_, response_code);
  }
  if (response_code == 200) {
    const net::HttpVersion required_version(1, 1);
    if (request->response_info().headers->GetParsedHttpVersion() <
        required_version) {
      Finished(BAD_HTTP_VERSION);
    } else {
      read_buffer_ = new net::IOBuffer(info_.expected_response.length());
      DoRead();
    }
  } else {
    Finished(BAD_RESPONSE_CODE);
  }
}

void HttpPipeliningCompatibilityClient::Request::OnReadCompleted(
    net::URLRequest* request,
    int bytes_read) {
  if (bytes_read == 0) {
    DoReadFinished();
  } else if (bytes_read < 0) {
    Finished(NETWORK_ERROR);
  } else {
    response_.append(read_buffer_->data(), bytes_read);
    if (response_.length() <= info_.expected_response.length()) {
      DoRead();
    } else if (response_.find(info_.expected_response) == 0) {
      Finished(TOO_LARGE);
    } else {
      Finished(CONTENT_MISMATCH);
    }
  }
}

void HttpPipeliningCompatibilityClient::Request::DoRead() {
  int bytes_read = 0;
  if (request_->Read(read_buffer_.get(), info_.expected_response.length(),
                     &bytes_read)) {
    OnReadCompleted(request_.get(), bytes_read);
  }
}

void HttpPipeliningCompatibilityClient::Request::DoReadFinished() {
  if (response_.length() != info_.expected_response.length()) {
    if (info_.expected_response.find(response_) == 0) {
      Finished(TOO_SMALL);
    } else {
      Finished(CONTENT_MISMATCH);
    }
  } else if (response_ == info_.expected_response) {
    Finished(SUCCESS);
  } else {
    Finished(CONTENT_MISMATCH);
  }
}

void HttpPipeliningCompatibilityClient::Request::Finished(Status result) {
  const net::URLRequestStatus status = request_->status();
  request_.reset();
  if (status.status() == net::URLRequestStatus::FAILED) {
    // Network errors trump all other status codes, because network errors can
    // be detected by the network stack even with real content. If we determine
    // that all pipelining errors can be detected by the network stack, then we
    // don't need to worry about broken proxies.
    client_->ReportNetworkError(request_id_, status.error());
    client_->OnRequestFinished(request_id_, NETWORK_ERROR);
  } else {
    client_->OnRequestFinished(request_id_, result);
  }
  // WARNING: We may be deleted at this point.
}

HttpPipeliningCompatibilityClient::StatsRequest::StatsRequest(
    int request_id,
    const std::string& base_url,
    const RequestInfo& info,
    HttpPipeliningCompatibilityClient* client,
    net::URLRequestContext* url_request_context)
    : Request(request_id, base_url, info, client, url_request_context) {
}

HttpPipeliningCompatibilityClient::StatsRequest::~StatsRequest() {
}

void HttpPipeliningCompatibilityClient::StatsRequest::DoReadFinished() {
  Status status = internal::ProcessStatsResponse(response());
  Finished(status);
}

namespace internal {

HttpPipeliningCompatibilityClient::Status ProcessStatsResponse(
    const std::string& response) {
  bool were_all_requests_http_1_1 = false;
  int max_pipeline_depth = 0;

  std::vector<std::pair<std::string, std::string> > kv_pairs;
  base::SplitStringIntoKeyValuePairs(response, ':', ',', &kv_pairs);

  if (kv_pairs.size() != 2) {
    return HttpPipeliningCompatibilityClient::CORRUPT_STATS;
  }

  for (size_t i = 0; i < kv_pairs.size(); ++i) {
    const std::string& key = kv_pairs[i].first;
    int value;
    if (!base::StringToInt(kv_pairs[i].second, &value)) {
      return HttpPipeliningCompatibilityClient::CORRUPT_STATS;
    }

    if (key == "were_all_requests_http_1_1") {
      were_all_requests_http_1_1 = (value == 1);
    } else if (key == "max_pipeline_depth") {
      max_pipeline_depth = value;
    } else {
      return HttpPipeliningCompatibilityClient::CORRUPT_STATS;
    }
  }

  UMA_HISTOGRAM_BOOLEAN("NetConnectivity.Pipeline.AllHTTP11",
                        were_all_requests_http_1_1);
  UMA_HISTOGRAM_ENUMERATION("NetConnectivity.Pipeline.Depth",
                            max_pipeline_depth, 6);

  return HttpPipeliningCompatibilityClient::SUCCESS;
}

}  // namespace internal

namespace {

void DeleteClient(HttpPipeliningCompatibilityClient* client, int rv) {
  delete client;
}

void CollectPipeliningCapabilityStatsOnIOThread(
    const std::string& pipeline_test_server,
    net::URLRequestContextGetter* url_request_context_getter) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  net::URLRequestContext* url_request_context =
      url_request_context_getter->GetURLRequestContext();
  if (!url_request_context->proxy_service()->config().proxy_rules().empty()) {
    // Pipelining with explicitly configured proxies is disabled for now.
    return;
  }

  const base::FieldTrial::Probability kDivisor = 100;
  base::FieldTrial::Probability probability_to_run_test = 0;

  const char* kTrialName = "HttpPipeliningCompatibility";
  base::FieldTrial* trial = base::FieldTrialList::Find(kTrialName);
  if (trial) {
    return;
  }
  // After April 1, 2012, the trial will disable itself.
  trial = new base::FieldTrial(kTrialName, kDivisor,
                               "disable_test", 2012, 4, 1);

  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel == chrome::VersionInfo::CHANNEL_CANARY) {
    probability_to_run_test = 100;
  }

  int collect_stats_group = trial->AppendGroup("enable_test",
                                               probability_to_run_test);
  if (trial->group() != collect_stats_group) {
    return;
  }

  std::vector<HttpPipeliningCompatibilityClient::RequestInfo> requests;

  HttpPipeliningCompatibilityClient::RequestInfo info0;
  info0.filename = "alphabet.txt";
  info0.expected_response = "abcdefghijklmnopqrstuvwxyz";
  requests.push_back(info0);

  HttpPipeliningCompatibilityClient::RequestInfo info1;
  info1.filename = "cached.txt";
  info1.expected_response = "azbycxdwevfugthsirjqkplomn";
  requests.push_back(info1);

  HttpPipeliningCompatibilityClient::RequestInfo info2;
  info2.filename = "reverse.txt";
  info2.expected_response = "zyxwvutsrqponmlkjihgfedcba";
  requests.push_back(info2);

  HttpPipeliningCompatibilityClient::RequestInfo info3;
  info3.filename = "chunked.txt";
  info3.expected_response = "chunkedencodingisfun";
  requests.push_back(info3);

  HttpPipeliningCompatibilityClient::RequestInfo info4;
  info4.filename = "cached.txt";
  info4.expected_response = "azbycxdwevfugthsirjqkplomn";
  requests.push_back(info4);

  HttpPipeliningCompatibilityClient* client =
      new HttpPipeliningCompatibilityClient;
  client->Start(pipeline_test_server, requests, true,
                base::Bind(&DeleteClient, client),
                url_request_context_getter->GetURLRequestContext());
}

}  // anonymous namespace

void CollectPipeliningCapabilityStatsOnUIThread(
    const std::string& pipeline_test_server, IOThread* io_thread) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (pipeline_test_server.empty())
    return;

  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&CollectPipeliningCapabilityStatsOnIOThread,
                 pipeline_test_server,
                 make_scoped_refptr(
                     io_thread->system_url_request_context_getter())));
}

}  // namespace chrome_browser_net
<commit_msg>Asynchronously delete pipeline compatibility test.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/net/http_pipelining_compatibility_client.h"

#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/stringprintf.h"
#include "chrome/browser/io_thread.h"
#include "chrome/common/chrome_version_info.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/load_flags.h"
#include "net/base/network_change_notifier.h"
#include "net/disk_cache/histogram_macros.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_network_session.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_version.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/url_request_context_getter.h"

namespace chrome_browser_net {

HttpPipeliningCompatibilityClient::HttpPipeliningCompatibilityClient()
    : num_finished_(0),
      num_succeeded_(0) {
}

HttpPipeliningCompatibilityClient::~HttpPipeliningCompatibilityClient() {
}

void HttpPipeliningCompatibilityClient::Start(
    const std::string& base_url,
    std::vector<RequestInfo>& requests,
    bool collect_server_stats,
    const net::CompletionCallback& callback,
    net::URLRequestContext* url_request_context) {
  net::HttpNetworkSession* old_session =
      url_request_context->http_transaction_factory()->GetSession();
  net::HttpNetworkSession::Params params = old_session->params();
  params.force_http_pipelining = true;
  scoped_refptr<net::HttpNetworkSession> session =
      new net::HttpNetworkSession(params);
  http_transaction_factory_.reset(
      net::HttpNetworkLayer::CreateFactory(session.get()));

  url_request_context_ = new net::URLRequestContext;
  url_request_context_->CopyFrom(url_request_context);
  url_request_context_->set_http_transaction_factory(
      http_transaction_factory_.get());

  finished_callback_ = callback;
  for (size_t i = 0; i < requests.size(); ++i) {
    requests_.push_back(new Request(i, base_url, requests[i], this,
                                    url_request_context_.get()));
  }
  if (collect_server_stats) {
    RequestInfo info;
    info.filename = "stats.txt";
    // This is just to determine the expected length of the response.
    // StatsRequest doesn't expect this exact value, but it does expect this
    // exact length.
    info.expected_response =
        "were_all_requests_http_1_1:1,max_pipeline_depth:5";
    requests_.push_back(new StatsRequest(requests.size(), base_url, info, this,
                                         url_request_context_.get()));
  }
}

void HttpPipeliningCompatibilityClient::OnRequestFinished(int request_id,
                                                          Status status) {
  // The CACHE_HISTOGRAM_* macros are used, because they allow dynamic metric
  // names.
  CACHE_HISTOGRAM_ENUMERATION(GetMetricName(request_id, "Status"),
                              status, STATUS_MAX);
  ++num_finished_;
  if (status == SUCCESS) {
    ++num_succeeded_;
  }
  if (num_finished_ == requests_.size()) {
    UMA_HISTOGRAM_BOOLEAN("NetConnectivity.Pipeline.Success",
                          num_succeeded_ == requests_.size());
    finished_callback_.Run(0);
  }
}

void HttpPipeliningCompatibilityClient::ReportNetworkError(int request_id,
                                                           int error_code) {
  CACHE_HISTOGRAM_ENUMERATION(GetMetricName(request_id, "NetworkError"),
                              -error_code, 900);
}

void HttpPipeliningCompatibilityClient::ReportResponseCode(int request_id,
                                                           int response_code) {
  CACHE_HISTOGRAM_ENUMERATION(GetMetricName(request_id, "ResponseCode"),
                              response_code, 600);
}

std::string HttpPipeliningCompatibilityClient::GetMetricName(
    int request_id, const char* description) {
  return base::StringPrintf("NetConnectivity.Pipeline.%d.%s",
                            request_id, description);
}

HttpPipeliningCompatibilityClient::Request::Request(
    int request_id,
    const std::string& base_url,
    const RequestInfo& info,
    HttpPipeliningCompatibilityClient* client,
    net::URLRequestContext* url_request_context)
    : request_id_(request_id),
      request_(new net::URLRequest(GURL(base_url + info.filename), this)),
      info_(info),
      client_(client) {
  request_->set_context(url_request_context);
  request_->set_load_flags(net::LOAD_BYPASS_CACHE |
                           net::LOAD_DISABLE_CACHE |
                           net::LOAD_DO_NOT_SAVE_COOKIES |
                           net::LOAD_DO_NOT_SEND_COOKIES |
                           net::LOAD_DO_NOT_PROMPT_FOR_LOGIN |
                           net::LOAD_DO_NOT_SEND_AUTH_DATA);
  request_->Start();
}

HttpPipeliningCompatibilityClient::Request::~Request() {
}

void HttpPipeliningCompatibilityClient::Request::OnReceivedRedirect(
    net::URLRequest* request,
    const GURL& new_url,
    bool* defer_redirect) {
  *defer_redirect = true;
  request->Cancel();
  Finished(REDIRECTED);
}

void HttpPipeliningCompatibilityClient::Request::OnSSLCertificateError(
    net::URLRequest* request,
    const net::SSLInfo& ssl_info,
    bool fatal) {
  Finished(CERT_ERROR);
}

void HttpPipeliningCompatibilityClient::Request::OnResponseStarted(
    net::URLRequest* request) {
  int response_code = request->GetResponseCode();
  if (response_code > 0) {
    client_->ReportResponseCode(request_id_, response_code);
  }
  if (response_code == 200) {
    const net::HttpVersion required_version(1, 1);
    if (request->response_info().headers->GetParsedHttpVersion() <
        required_version) {
      Finished(BAD_HTTP_VERSION);
    } else {
      read_buffer_ = new net::IOBuffer(info_.expected_response.length());
      DoRead();
    }
  } else {
    Finished(BAD_RESPONSE_CODE);
  }
}

void HttpPipeliningCompatibilityClient::Request::OnReadCompleted(
    net::URLRequest* request,
    int bytes_read) {
  if (bytes_read == 0) {
    DoReadFinished();
  } else if (bytes_read < 0) {
    Finished(NETWORK_ERROR);
  } else {
    response_.append(read_buffer_->data(), bytes_read);
    if (response_.length() <= info_.expected_response.length()) {
      DoRead();
    } else if (response_.find(info_.expected_response) == 0) {
      Finished(TOO_LARGE);
    } else {
      Finished(CONTENT_MISMATCH);
    }
  }
}

void HttpPipeliningCompatibilityClient::Request::DoRead() {
  int bytes_read = 0;
  if (request_->Read(read_buffer_.get(), info_.expected_response.length(),
                     &bytes_read)) {
    OnReadCompleted(request_.get(), bytes_read);
  }
}

void HttpPipeliningCompatibilityClient::Request::DoReadFinished() {
  if (response_.length() != info_.expected_response.length()) {
    if (info_.expected_response.find(response_) == 0) {
      Finished(TOO_SMALL);
    } else {
      Finished(CONTENT_MISMATCH);
    }
  } else if (response_ == info_.expected_response) {
    Finished(SUCCESS);
  } else {
    Finished(CONTENT_MISMATCH);
  }
}

void HttpPipeliningCompatibilityClient::Request::Finished(Status result) {
  const net::URLRequestStatus status = request_->status();
  request_.reset();
  if (status.status() == net::URLRequestStatus::FAILED) {
    // Network errors trump all other status codes, because network errors can
    // be detected by the network stack even with real content. If we determine
    // that all pipelining errors can be detected by the network stack, then we
    // don't need to worry about broken proxies.
    client_->ReportNetworkError(request_id_, status.error());
    client_->OnRequestFinished(request_id_, NETWORK_ERROR);
  } else {
    client_->OnRequestFinished(request_id_, result);
  }
  // WARNING: We may be deleted at this point.
}

HttpPipeliningCompatibilityClient::StatsRequest::StatsRequest(
    int request_id,
    const std::string& base_url,
    const RequestInfo& info,
    HttpPipeliningCompatibilityClient* client,
    net::URLRequestContext* url_request_context)
    : Request(request_id, base_url, info, client, url_request_context) {
}

HttpPipeliningCompatibilityClient::StatsRequest::~StatsRequest() {
}

void HttpPipeliningCompatibilityClient::StatsRequest::DoReadFinished() {
  Status status = internal::ProcessStatsResponse(response());
  Finished(status);
}

namespace internal {

HttpPipeliningCompatibilityClient::Status ProcessStatsResponse(
    const std::string& response) {
  bool were_all_requests_http_1_1 = false;
  int max_pipeline_depth = 0;

  std::vector<std::pair<std::string, std::string> > kv_pairs;
  base::SplitStringIntoKeyValuePairs(response, ':', ',', &kv_pairs);

  if (kv_pairs.size() != 2) {
    return HttpPipeliningCompatibilityClient::CORRUPT_STATS;
  }

  for (size_t i = 0; i < kv_pairs.size(); ++i) {
    const std::string& key = kv_pairs[i].first;
    int value;
    if (!base::StringToInt(kv_pairs[i].second, &value)) {
      return HttpPipeliningCompatibilityClient::CORRUPT_STATS;
    }

    if (key == "were_all_requests_http_1_1") {
      were_all_requests_http_1_1 = (value == 1);
    } else if (key == "max_pipeline_depth") {
      max_pipeline_depth = value;
    } else {
      return HttpPipeliningCompatibilityClient::CORRUPT_STATS;
    }
  }

  UMA_HISTOGRAM_BOOLEAN("NetConnectivity.Pipeline.AllHTTP11",
                        were_all_requests_http_1_1);
  UMA_HISTOGRAM_ENUMERATION("NetConnectivity.Pipeline.Depth",
                            max_pipeline_depth, 6);

  return HttpPipeliningCompatibilityClient::SUCCESS;
}

}  // namespace internal

namespace {

void DeleteClient(HttpPipeliningCompatibilityClient* client) {
  delete client;
}

void DelayedDeleteClient(HttpPipeliningCompatibilityClient* client, int rv) {
  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&DeleteClient, client));
}

void CollectPipeliningCapabilityStatsOnIOThread(
    const std::string& pipeline_test_server,
    net::URLRequestContextGetter* url_request_context_getter) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

  net::URLRequestContext* url_request_context =
      url_request_context_getter->GetURLRequestContext();
  if (!url_request_context->proxy_service()->config().proxy_rules().empty()) {
    // Pipelining with explicitly configured proxies is disabled for now.
    return;
  }

  const base::FieldTrial::Probability kDivisor = 100;
  base::FieldTrial::Probability probability_to_run_test = 0;

  const char* kTrialName = "HttpPipeliningCompatibility";
  base::FieldTrial* trial = base::FieldTrialList::Find(kTrialName);
  if (trial) {
    return;
  }
  // After April 1, 2012, the trial will disable itself.
  trial = new base::FieldTrial(kTrialName, kDivisor,
                               "disable_test", 2012, 4, 1);

  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  if (channel == chrome::VersionInfo::CHANNEL_CANARY) {
    probability_to_run_test = 100;
  }

  int collect_stats_group = trial->AppendGroup("enable_test",
                                               probability_to_run_test);
  if (trial->group() != collect_stats_group) {
    return;
  }

  std::vector<HttpPipeliningCompatibilityClient::RequestInfo> requests;

  HttpPipeliningCompatibilityClient::RequestInfo info0;
  info0.filename = "alphabet.txt";
  info0.expected_response = "abcdefghijklmnopqrstuvwxyz";
  requests.push_back(info0);

  HttpPipeliningCompatibilityClient::RequestInfo info1;
  info1.filename = "cached.txt";
  info1.expected_response = "azbycxdwevfugthsirjqkplomn";
  requests.push_back(info1);

  HttpPipeliningCompatibilityClient::RequestInfo info2;
  info2.filename = "reverse.txt";
  info2.expected_response = "zyxwvutsrqponmlkjihgfedcba";
  requests.push_back(info2);

  HttpPipeliningCompatibilityClient::RequestInfo info3;
  info3.filename = "chunked.txt";
  info3.expected_response = "chunkedencodingisfun";
  requests.push_back(info3);

  HttpPipeliningCompatibilityClient::RequestInfo info4;
  info4.filename = "cached.txt";
  info4.expected_response = "azbycxdwevfugthsirjqkplomn";
  requests.push_back(info4);

  HttpPipeliningCompatibilityClient* client =
      new HttpPipeliningCompatibilityClient;
  client->Start(pipeline_test_server, requests, true,
                base::Bind(&DelayedDeleteClient, client),
                url_request_context_getter->GetURLRequestContext());
}

}  // anonymous namespace

void CollectPipeliningCapabilityStatsOnUIThread(
    const std::string& pipeline_test_server, IOThread* io_thread) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (pipeline_test_server.empty())
    return;

  content::BrowserThread::PostTask(
      content::BrowserThread::IO,
      FROM_HERE,
      base::Bind(&CollectPipeliningCapabilityStatsOnIOThread,
                 pipeline_test_server,
                 make_scoped_refptr(
                     io_thread->system_url_request_context_getter())));
}

}  // namespace chrome_browser_net
<|endoftext|>


<commit_before>//- ------------------------------------------------------------------
//-    Copyright (c) Changjiang. Liu -- All Rights Reserved
//-    Licensed under the Apache License, Version 2.0 (the "License").
//-
//-    Available at https://github.com/rookiecalf/IQmath_fake
//-
//-
//-    Authorized users may use this source code in your own
//-    projects. We make no guarantees that this source code is
//-    fit for any purpose.
//-
//-    softci.com    rookiecalf@gmail.com
//- ------------------------------------------------------------------

#include "CppUTest/TestHarness.h"

extern "C"
{
	#include "IQmathLib.h"
}

TEST_GROUP(IQmath_Exponentiation)
{
    void setup()
    {

    }

    void teardown()
    {

    }

};

TEST(IQmath_Exponentiation, IQ1exp)
{
    LONGS_EQUAL(_IQ1(2.25), _IQ1exp(_IQ1(1.5))) ;
	LONGS_EQUAL(_IQ1(6.25), _IQ1exp(_IQ1(2.5))) ;
}

<commit_msg>添加IQ1exp负数测试用例。<commit_after>//- ------------------------------------------------------------------
//-    Copyright (c) Changjiang. Liu -- All Rights Reserved
//-    Licensed under the Apache License, Version 2.0 (the "License").
//-
//-    Available at https://github.com/rookiecalf/IQmath_fake
//-
//-
//-    Authorized users may use this source code in your own
//-    projects. We make no guarantees that this source code is
//-    fit for any purpose.
//-
//-    softci.com    rookiecalf@gmail.com
//- ------------------------------------------------------------------

#include "CppUTest/TestHarness.h"

extern "C"
{
	#include "IQmathLib.h"
}

TEST_GROUP(IQmath_Exponentiation)
{
    void setup()
    {

    }

    void teardown()
    {

    }

};

TEST(IQmath_Exponentiation, IQ1exp)
{
    LONGS_EQUAL(_IQ1(2.25), _IQ1exp(_IQ1(1.5))) ;
	LONGS_EQUAL(_IQ1(6.25), _IQ1exp(_IQ1(2.5))) ;
}

TEST(IQmath_Exponentiation, IQ1expNegative)
{
    LONGS_EQUAL(_IQ1(2.25), _IQ1exp(_IQ1(-1.5))) ;
	LONGS_EQUAL(_IQ1(6.25), _IQ1exp(_IQ1(-2.5))) ;
}

<|endoftext|>


<commit_before>#include "Vajra/Engine/AssetLibrary/Assets/TextureAssets/TextureAsset.h"
#include "Vajra/Framework/Core/Framework.h"
#include "Vajra/Framework/Loaders/TextureLoader/TextureLoader.h"
#include "Vajra/Framework/Logging/Logger.h"
#include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h"
#include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h"
#include "Vajra/Utilities/Utilities.h"

AssetType TextureAsset::assetType = ASSET_TYPE_GL_TEXTURE;

TextureAsset::TextureAsset() : Asset() {
	this->init();
}

TextureAsset::TextureAsset(std::string urlOfTexture) : Asset(urlOfTexture) {
	this->init();
}

TextureAsset::~TextureAsset() {
	this->destroy();
}

void TextureAsset::init() {
	this->textureGLHandle = 0;
}

void TextureAsset::destroy() {
	if (this->textureGLHandle != 0) {
		FRAMEWORK->GetOpenGLWrapper()->FreeGLTexture(&this->textureGLHandle);
	}
	// TODO [Implement] Figure out if any other cleanup is necessary to free up allocated opengl texture memory
}

void TextureAsset::Draw(GLint drawAsTextureUnit) {

	ShaderSet* currentShaderSet = FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet();

	switch (drawAsTextureUnit) {
	case 0: {
		if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_myTextureSampler)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_myTextureSampler);

			GLCALL(glActiveTexture, GL_TEXTURE0);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);
		}
	} break;

	case 1: {
		if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_bakedAmbientGridTextureSampler)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_bakedAmbientGridTextureSampler);

			GLCALL(glActiveTexture, GL_TEXTURE1);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);
		}
	} break;

	case 2: {
		ASSERT(0, "Whoa. This is where the depth texture plugs in for shadows");
	} break;

	case 3: {
		if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_secondaryTexture)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_secondaryTexture);

			GLCALL(glActiveTexture, GL_TEXTURE3);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);

		} else if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_normalMap)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_normalMap);

			GLCALL(glActiveTexture, GL_TEXTURE3);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);
		}
	} break;

	default: {
		FRAMEWORK->GetLogger()->dbglog("\nValid texture unit %d", drawAsTextureUnit);
	} break;

	}

}

AssetType TextureAsset::GetAssetType() {
	return TextureAsset::assetType;
}

void TextureAsset::LoadAsset() {
	ASSERT(this->GetUrl() != "", "Url set when trying to load texture asset");

	FRAMEWORK->GetLogger()->dbglog("\nLoading texture asset from url: %s", this->GetFilePathToTexture().c_str());

	// TODO [Implement] Move loadGLTextureFromPNG into a Framework class/namespace
    // Load image
	GLubyte* textureBytes = nullptr;
    this->textureGLHandle = loadGLTextureFromPNG(this->GetFilePathToTexture().c_str(), &(textureBytes));
    ASSERT(this->textureGLHandle != 0 && textureBytes != nullptr, "Successfully loaded texture from url %s", this->GetFilePathToTexture().c_str());

    // Free up the texture bytes in ram now that it's in the gpu:
	if (textureBytes != nullptr) {
		free(textureBytes);
	}
	textureBytes = nullptr;
}

std::string TextureAsset::GetFilePathToTexture() {
	return this->GetUrl();
}
<commit_msg>Fixed for IOS deployment<commit_after>#include "Vajra/Engine/AssetLibrary/Assets/TextureAssets/TextureAsset.h"
#include "Vajra/Framework/Core/Framework.h"
#include "Vajra/Framework/Loaders/TextureLoader/TextureLoader.h"
#include "Vajra/Framework/Logging/Logger.h"
#include "Vajra/Framework/OpenGL/OpenGLWrapper/OpenGLWrapper.h"
#include "Vajra/Framework/OpenGL/ShaderSet/ShaderSet.h"
#include "Vajra/Utilities/Utilities.h"

AssetType TextureAsset::assetType = ASSET_TYPE_GL_TEXTURE;

TextureAsset::TextureAsset() : Asset() {
	this->init();
}

TextureAsset::TextureAsset(std::string urlOfTexture) : Asset(urlOfTexture) {
	this->init();
}

TextureAsset::~TextureAsset() {
	this->destroy();
}

void TextureAsset::init() {
	this->textureGLHandle = 0;
}

void TextureAsset::destroy() {
	if (this->textureGLHandle != 0) {
		FRAMEWORK->GetOpenGLWrapper()->FreeGLTexture(&this->textureGLHandle);
	}
	// TODO [Implement] Figure out if any other cleanup is necessary to free up allocated opengl texture memory
}

void TextureAsset::Draw(GLint drawAsTextureUnit) {

	ShaderSet* currentShaderSet = FRAMEWORK->GetOpenGLWrapper()->GetCurrentShaderSet();

	switch (drawAsTextureUnit) {
	case 0: {
		if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_myTextureSampler)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_myTextureSampler);

			GLCALL(glActiveTexture, GL_TEXTURE0);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);
		}
	} break;

	case 1: {
		if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_bakedAmbientGridTextureSampler)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_bakedAmbientGridTextureSampler);

			GLCALL(glActiveTexture, GL_TEXTURE1);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);
		}
	} break;

	case 2: {
		ASSERT(0, "Whoa. This is where the depth texture plugs in for shadows");
	} break;

	case 3: {
		if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_secondaryTexture)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_secondaryTexture);

			GLCALL(glActiveTexture, GL_TEXTURE3);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);

		} else if (currentShaderSet->HasHandle(SHADER_VARIABLE_VARIABLENAME_normalMap)) {
			GLint textureHandle = currentShaderSet->GetHandle(SHADER_VARIABLE_VARIABLENAME_normalMap);

			GLCALL(glActiveTexture, GL_TEXTURE3);
			GLCALL(glBindTexture, GL_TEXTURE_2D, this->textureGLHandle);
			GLCALL(glUniform1i, textureHandle, drawAsTextureUnit);
		}
	} break;

	default: {
		FRAMEWORK->GetLogger()->dbglog("\nValid texture unit %d", drawAsTextureUnit);
	} break;

	}

}

AssetType TextureAsset::GetAssetType() {
	return TextureAsset::assetType;
}

void TextureAsset::LoadAsset() {
	ASSERT(this->GetUrl() != "", "Url set when trying to load texture asset");

	FRAMEWORK->GetLogger()->dbglog("\nLoading texture asset from url: %s", this->GetFilePathToTexture().c_str());

	// TODO [Implement] Move loadGLTextureFromPNG into a Framework class/namespace
    // Load image
	GLubyte* textureBytes = nullptr;
    this->textureGLHandle = loadGLTextureFromPNG(this->GetFilePathToTexture().c_str(), &(textureBytes));
    ASSERT(this->textureGLHandle != 0 && textureBytes != nullptr, "Successfully loaded texture from url %s", this->GetFilePathToTexture().c_str());

    // Free up the texture bytes in ram now that it's in the gpu:
	if (textureBytes != nullptr) {
#if !defined(PLATFORM_IOS)
		free(textureBytes);
#endif
	}
	textureBytes = nullptr;
}

std::string TextureAsset::GetFilePathToTexture() {
	return this->GetUrl();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: srchdefs.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-04-11 21:29:55 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SFX_SRCHDEFS_HXX_
#define _SFX_SRCHDEFS_HXX_

#define SEARCH_OPTIONS_SEARCH       ((sal_uInt16)0x0001)
#define SEARCH_OPTIONS_SEARCH_ALL   ((sal_uInt16)0x0002)
#define SEARCH_OPTIONS_REPLACE      ((sal_uInt16)0x0004)
#define SEARCH_OPTIONS_REPLACE_ALL  ((sal_uInt16)0x0008)
#define SEARCH_OPTIONS_WHOLE_WORDS  ((sal_uInt16)0x0010)
#define SEARCH_OPTIONS_BACKWARDS    ((sal_uInt16)0x0020)
#define SEARCH_OPTIONS_REG_EXP      ((sal_uInt16)0x0040)
#define SEARCH_OPTIONS_EXACT        ((sal_uInt16)0x0080)
#define SEARCH_OPTIONS_SELECTION    ((sal_uInt16)0x0100)
#define SEARCH_OPTIONS_FAMILIES     ((sal_uInt16)0x0200)
#define SEARCH_OPTIONS_FORMAT       ((sal_uInt16)0x0400)
#define SEARCH_OPTIONS_MORE         ((sal_uInt16)0x0800)
#define SEARCH_OPTIONS_SIMILARITY   ((sal_uInt16)0x1000)
#define SEARCH_OPTIONS_CONTENT      ((sal_uInt16)0x2000)

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.2.280); FILE MERGED 2008/03/31 13:37:57 rt 1.2.280.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: srchdefs.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SFX_SRCHDEFS_HXX_
#define _SFX_SRCHDEFS_HXX_

#define SEARCH_OPTIONS_SEARCH       ((sal_uInt16)0x0001)
#define SEARCH_OPTIONS_SEARCH_ALL   ((sal_uInt16)0x0002)
#define SEARCH_OPTIONS_REPLACE      ((sal_uInt16)0x0004)
#define SEARCH_OPTIONS_REPLACE_ALL  ((sal_uInt16)0x0008)
#define SEARCH_OPTIONS_WHOLE_WORDS  ((sal_uInt16)0x0010)
#define SEARCH_OPTIONS_BACKWARDS    ((sal_uInt16)0x0020)
#define SEARCH_OPTIONS_REG_EXP      ((sal_uInt16)0x0040)
#define SEARCH_OPTIONS_EXACT        ((sal_uInt16)0x0080)
#define SEARCH_OPTIONS_SELECTION    ((sal_uInt16)0x0100)
#define SEARCH_OPTIONS_FAMILIES     ((sal_uInt16)0x0200)
#define SEARCH_OPTIONS_FORMAT       ((sal_uInt16)0x0400)
#define SEARCH_OPTIONS_MORE         ((sal_uInt16)0x0800)
#define SEARCH_OPTIONS_SIMILARITY   ((sal_uInt16)0x1000)
#define SEARCH_OPTIONS_CONTENT      ((sal_uInt16)0x2000)

#endif

<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreShaderExTriplanarTexturing.h"
#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS
#include "OgreShaderFFPRenderState.h"
#include "OgreShaderProgram.h"
#include "OgreShaderParameter.h"
#include "OgreShaderProgramSet.h"

namespace Ogre {
namespace RTShader {

    String TriplanarTexturing::type = "SGX_TriplanarTexturing";

    //-----------------------------------------------------------------------

    bool TriplanarTexturing::resolveParameters(ProgramSet* programSet)
    {
        Program* vsProgram = programSet->getCpuVertexProgram();
        Program* psProgram = programSet->getCpuFragmentProgram();
        Function* vsMain   = vsProgram->getEntryPointFunction();
        Function* psMain   = psProgram->getEntryPointFunction();

        // Resolve pixel shader output diffuse color.
        mPSInDiffuse = vsMain->resolveInputParameter(Parameter::SPS_COLOR, 0, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4);

        // Resolve input vertex shader normal.
        mVSInNormal = vsMain->resolveInputParameter(Parameter::SPS_NORMAL, 0, Parameter::SPC_NORMAL_OBJECT_SPACE, GCT_FLOAT3);

        // Resolve output vertex shader normal.
        mVSOutNormal = vsMain->resolveOutputParameter(Parameter::SPS_TEXTURE_COORDINATES, -1, Parameter::SPC_NORMAL_VIEW_SPACE, GCT_FLOAT3);

        // Resolve input pixel shader normal.
        mPSInNormal = psMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES,
            mVSOutNormal->getIndex(),
            mVSOutNormal->getContent(),
            GCT_FLOAT3);

        // Resolve input vertex shader normal.
        mVSInPosition = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);

        mVSInPosition  = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);
        mVSOutPosition = vsMain->resolveOutputParameter(Parameter::SPS_TEXTURE_COORDINATES, -1, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);
        mPSInPosition = psMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES,
            mVSOutPosition->getIndex(),
            mVSOutPosition->getContent(),
            GCT_FLOAT4);

        mSamplerFromX = psProgram->resolveParameter(GCT_SAMPLER2D, mTextureSamplerIndexFromX, (uint16)GPV_GLOBAL, "tp_sampler_from_x");
        if (mSamplerFromX.get() == NULL)
            return false;
        mSamplerFromY = psProgram->resolveParameter(GCT_SAMPLER2D, mTextureSamplerIndexFromY, (uint16)GPV_GLOBAL, "tp_sampler_from_y");
        if (mSamplerFromY.get() == NULL)
            return false;
        mSamplerFromZ = psProgram->resolveParameter(GCT_SAMPLER2D, mTextureSamplerIndexFromZ, (uint16)GPV_GLOBAL, "tp_sampler_from_z");
        if (mSamplerFromZ.get() == NULL)
            return false;

        mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPS_COLOR, 0, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4);
        if (mPSOutDiffuse.get() == NULL)
            return false;

        mPSTPParams = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_GLOBAL, "gTPParams");
        if (mPSTPParams.get() == NULL)
            return false;
        return true;
    }

    //-----------------------------------------------------------------------
    bool TriplanarTexturing::resolveDependencies(ProgramSet* programSet)
    {
        Program* psProgram = programSet->getCpuFragmentProgram();
        Program* vsProgram = programSet->getCpuVertexProgram();
        psProgram->addDependency("SGXLib_TriplanarTexturing");
        vsProgram->addDependency(FFP_LIB_COMMON);
        return true;
    }

    //-----------------------------------------------------------------------
    bool TriplanarTexturing::addFunctionInvocations(ProgramSet* programSet)
    {
        Program* psProgram = programSet->getCpuFragmentProgram();
        Function* psMain = psProgram->getEntryPointFunction();
        Program* vsProgram = programSet->getCpuVertexProgram();
        Function* vsMain = vsProgram->getEntryPointFunction();

        size_t internalCounter = 0;

        FunctionInvocation *curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, FFP_VS_TEXTURING, internalCounter++);
        curFuncInvocation->pushOperand(mVSInNormal, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mVSOutNormal, Operand::OPS_OUT);
        vsMain->addAtomInstance(curFuncInvocation);

        curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, FFP_VS_TEXTURING, internalCounter++);
        curFuncInvocation->pushOperand(mVSInPosition, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mVSOutPosition, Operand::OPS_OUT);
        vsMain->addAtomInstance(curFuncInvocation);

        curFuncInvocation = OGRE_NEW FunctionInvocation(SGX_FUNC_TRIPLANAR_TEXTURING, FFP_PS_TEXTURING, internalCounter++);
        curFuncInvocation->pushOperand(mPSInDiffuse, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSInNormal, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSInPosition, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mSamplerFromX, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mSamplerFromY, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mSamplerFromZ, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSTPParams, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT);
        psMain->addAtomInstance(curFuncInvocation);

        return true;
    }

    //-----------------------------------------------------------------------
    const String& TriplanarTexturing::getType() const
    {
        return type;
    }

    //-----------------------------------------------------------------------
    int	TriplanarTexturing::getExecutionOrder() const
    {
        return FFP_TEXTURING;
    }

    //-----------------------------------------------------------------------
    bool TriplanarTexturing::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass )
    {
        TextureUnitState* textureUnit;

        // Create the mapping textures
        textureUnit = dstPass->createTextureUnitState();
        textureUnit->setTextureName(mTextureNameFromX);
        mTextureSamplerIndexFromX = dstPass->getNumTextureUnitStates() - 1;

        textureUnit = dstPass->createTextureUnitState();
        textureUnit->setTextureName(mTextureNameFromY);
        mTextureSamplerIndexFromY = dstPass->getNumTextureUnitStates() - 1;

        textureUnit = dstPass->createTextureUnitState();
        textureUnit->setTextureName(mTextureNameFromZ);
        mTextureSamplerIndexFromZ = dstPass->getNumTextureUnitStates() - 1;
        return true;
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::copyFrom(const SubRenderState& rhs)
    {
        const TriplanarTexturing& rhsTP = static_cast<const TriplanarTexturing&>(rhs);
        mPSOutDiffuse = rhsTP.mPSOutDiffuse;
        mPSInDiffuse = rhsTP.mPSInDiffuse;

        mVSInPosition = rhsTP.mVSInPosition;
        mVSOutPosition = rhsTP.mVSOutPosition;

        mVSOutNormal = rhsTP.mVSOutNormal;
        mVSInNormal = rhsTP.mVSInNormal;
        mPSInNormal = rhsTP.mPSInNormal;

        mVSOutPosition = rhsTP.mVSOutPosition;
        mVSInPosition = rhsTP.mVSInPosition;
        mPSInPosition = rhsTP.mPSInPosition;

        mSamplerFromX = rhsTP.mSamplerFromX;
        mSamplerFromY = rhsTP.mSamplerFromY;
        mSamplerFromZ = rhsTP.mSamplerFromZ;

        mPSTPParams = rhsTP.mPSTPParams;
        mParameters = rhsTP.mParameters;

        mTextureNameFromX = rhsTP.mTextureNameFromX;
        mTextureNameFromY = rhsTP.mTextureNameFromY;
        mTextureNameFromZ = rhsTP.mTextureNameFromZ;
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source,
                                         const LightList* pLightList)
    {
        mPSTPParams->setGpuParameter(mParameters);
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::setParameters(const Vector3 &parameters)
    {
        mParameters = parameters;
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::setTextureNames(const String &textureNameFromX, const String &textureNameFromY, const String &textureNameFromZ)
    {
        mTextureNameFromX = textureNameFromX;
        mTextureNameFromY = textureNameFromY;
        mTextureNameFromZ = textureNameFromZ;
    }

    //-----------------------------------------------------------------------
    const String& TriplanarTexturingFactory::getType() const
    {
        return TriplanarTexturing::type;
    }

    //-----------------------------------------------------------------------
    SubRenderState*	TriplanarTexturingFactory::createInstance(ScriptCompiler* compiler,
                                                       PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)
    {

        if (prop->name == "triplanarTexturing")
        {
            if (prop->values.size() == 6)
            {
                SubRenderState* subRenderState = createOrRetrieveInstance(translator);
                TriplanarTexturing* tpSubRenderState = static_cast<TriplanarTexturing*>(subRenderState);
                float parameters[3];
                ColourValue cValue;
                AbstractNodeList::const_iterator it = prop->values.begin();
                if (false == SGScriptTranslator::getFloat(*it, parameters))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getFloat(*it, parameters + 1))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getFloat(*it, parameters + 2))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                Vector3 vParameters(parameters[0], parameters[1], parameters[2]);
                tpSubRenderState->setParameters(vParameters);

                String textureNameFromX, textureNameFromY, textureNameFromZ;
                it++;
                if (false == SGScriptTranslator::getString(*it, &textureNameFromX))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getString(*it, &textureNameFromY))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getString(*it, &textureNameFromZ))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                tpSubRenderState->setTextureNames(textureNameFromX, textureNameFromY, textureNameFromZ);

                return subRenderState;
            }
            else
            {
                compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
            }
        }

        return NULL;
    }

    //-----------------------------------------------------------------------
    SubRenderState*	TriplanarTexturingFactory::createInstanceImpl()
    {
        return OGRE_NEW TriplanarTexturing;
    }

}
}

#endif
<commit_msg>RTSS: removed unused var<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2012 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreShaderExTriplanarTexturing.h"
#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS
#include "OgreShaderFFPRenderState.h"
#include "OgreShaderProgram.h"
#include "OgreShaderParameter.h"
#include "OgreShaderProgramSet.h"

namespace Ogre {
namespace RTShader {

    String TriplanarTexturing::type = "SGX_TriplanarTexturing";

    //-----------------------------------------------------------------------

    bool TriplanarTexturing::resolveParameters(ProgramSet* programSet)
    {
        Program* vsProgram = programSet->getCpuVertexProgram();
        Program* psProgram = programSet->getCpuFragmentProgram();
        Function* vsMain   = vsProgram->getEntryPointFunction();
        Function* psMain   = psProgram->getEntryPointFunction();

        // Resolve pixel shader output diffuse color.
        mPSInDiffuse = vsMain->resolveInputParameter(Parameter::SPS_COLOR, 0, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4);

        // Resolve input vertex shader normal.
        mVSInNormal = vsMain->resolveInputParameter(Parameter::SPS_NORMAL, 0, Parameter::SPC_NORMAL_OBJECT_SPACE, GCT_FLOAT3);

        // Resolve output vertex shader normal.
        mVSOutNormal = vsMain->resolveOutputParameter(Parameter::SPS_TEXTURE_COORDINATES, -1, Parameter::SPC_NORMAL_VIEW_SPACE, GCT_FLOAT3);

        // Resolve input pixel shader normal.
        mPSInNormal = psMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES,
            mVSOutNormal->getIndex(),
            mVSOutNormal->getContent(),
            GCT_FLOAT3);

        // Resolve input vertex shader normal.
        mVSInPosition = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);

        mVSInPosition  = vsMain->resolveInputParameter(Parameter::SPS_POSITION, 0, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);
        mVSOutPosition = vsMain->resolveOutputParameter(Parameter::SPS_TEXTURE_COORDINATES, -1, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4);
        mPSInPosition = psMain->resolveInputParameter(Parameter::SPS_TEXTURE_COORDINATES,
            mVSOutPosition->getIndex(),
            mVSOutPosition->getContent(),
            GCT_FLOAT4);

        mSamplerFromX = psProgram->resolveParameter(GCT_SAMPLER2D, mTextureSamplerIndexFromX, (uint16)GPV_GLOBAL, "tp_sampler_from_x");
        if (mSamplerFromX.get() == NULL)
            return false;
        mSamplerFromY = psProgram->resolveParameter(GCT_SAMPLER2D, mTextureSamplerIndexFromY, (uint16)GPV_GLOBAL, "tp_sampler_from_y");
        if (mSamplerFromY.get() == NULL)
            return false;
        mSamplerFromZ = psProgram->resolveParameter(GCT_SAMPLER2D, mTextureSamplerIndexFromZ, (uint16)GPV_GLOBAL, "tp_sampler_from_z");
        if (mSamplerFromZ.get() == NULL)
            return false;

        mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPS_COLOR, 0, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4);
        if (mPSOutDiffuse.get() == NULL)
            return false;

        mPSTPParams = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_GLOBAL, "gTPParams");
        if (mPSTPParams.get() == NULL)
            return false;
        return true;
    }

    //-----------------------------------------------------------------------
    bool TriplanarTexturing::resolveDependencies(ProgramSet* programSet)
    {
        Program* psProgram = programSet->getCpuFragmentProgram();
        Program* vsProgram = programSet->getCpuVertexProgram();
        psProgram->addDependency("SGXLib_TriplanarTexturing");
        vsProgram->addDependency(FFP_LIB_COMMON);
        return true;
    }

    //-----------------------------------------------------------------------
    bool TriplanarTexturing::addFunctionInvocations(ProgramSet* programSet)
    {
        Program* psProgram = programSet->getCpuFragmentProgram();
        Function* psMain = psProgram->getEntryPointFunction();
        Program* vsProgram = programSet->getCpuVertexProgram();
        Function* vsMain = vsProgram->getEntryPointFunction();

        size_t internalCounter = 0;

        FunctionInvocation *curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, FFP_VS_TEXTURING, internalCounter++);
        curFuncInvocation->pushOperand(mVSInNormal, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mVSOutNormal, Operand::OPS_OUT);
        vsMain->addAtomInstance(curFuncInvocation);

        curFuncInvocation = OGRE_NEW FunctionInvocation(FFP_FUNC_ASSIGN, FFP_VS_TEXTURING, internalCounter++);
        curFuncInvocation->pushOperand(mVSInPosition, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mVSOutPosition, Operand::OPS_OUT);
        vsMain->addAtomInstance(curFuncInvocation);

        curFuncInvocation = OGRE_NEW FunctionInvocation(SGX_FUNC_TRIPLANAR_TEXTURING, FFP_PS_TEXTURING, internalCounter++);
        curFuncInvocation->pushOperand(mPSInDiffuse, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSInNormal, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSInPosition, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mSamplerFromX, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mSamplerFromY, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mSamplerFromZ, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSTPParams, Operand::OPS_IN);
        curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT);
        psMain->addAtomInstance(curFuncInvocation);

        return true;
    }

    //-----------------------------------------------------------------------
    const String& TriplanarTexturing::getType() const
    {
        return type;
    }

    //-----------------------------------------------------------------------
    int	TriplanarTexturing::getExecutionOrder() const
    {
        return FFP_TEXTURING;
    }

    //-----------------------------------------------------------------------
    bool TriplanarTexturing::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass )
    {
        TextureUnitState* textureUnit;

        // Create the mapping textures
        textureUnit = dstPass->createTextureUnitState();
        textureUnit->setTextureName(mTextureNameFromX);
        mTextureSamplerIndexFromX = dstPass->getNumTextureUnitStates() - 1;

        textureUnit = dstPass->createTextureUnitState();
        textureUnit->setTextureName(mTextureNameFromY);
        mTextureSamplerIndexFromY = dstPass->getNumTextureUnitStates() - 1;

        textureUnit = dstPass->createTextureUnitState();
        textureUnit->setTextureName(mTextureNameFromZ);
        mTextureSamplerIndexFromZ = dstPass->getNumTextureUnitStates() - 1;
        return true;
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::copyFrom(const SubRenderState& rhs)
    {
        const TriplanarTexturing& rhsTP = static_cast<const TriplanarTexturing&>(rhs);
        mPSOutDiffuse = rhsTP.mPSOutDiffuse;
        mPSInDiffuse = rhsTP.mPSInDiffuse;

        mVSInPosition = rhsTP.mVSInPosition;
        mVSOutPosition = rhsTP.mVSOutPosition;

        mVSOutNormal = rhsTP.mVSOutNormal;
        mVSInNormal = rhsTP.mVSInNormal;
        mPSInNormal = rhsTP.mPSInNormal;

        mVSOutPosition = rhsTP.mVSOutPosition;
        mVSInPosition = rhsTP.mVSInPosition;
        mPSInPosition = rhsTP.mPSInPosition;

        mSamplerFromX = rhsTP.mSamplerFromX;
        mSamplerFromY = rhsTP.mSamplerFromY;
        mSamplerFromZ = rhsTP.mSamplerFromZ;

        mPSTPParams = rhsTP.mPSTPParams;
        mParameters = rhsTP.mParameters;

        mTextureNameFromX = rhsTP.mTextureNameFromX;
        mTextureNameFromY = rhsTP.mTextureNameFromY;
        mTextureNameFromZ = rhsTP.mTextureNameFromZ;
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source,
                                         const LightList* pLightList)
    {
        mPSTPParams->setGpuParameter(mParameters);
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::setParameters(const Vector3 &parameters)
    {
        mParameters = parameters;
    }

    //-----------------------------------------------------------------------
    void TriplanarTexturing::setTextureNames(const String &textureNameFromX, const String &textureNameFromY, const String &textureNameFromZ)
    {
        mTextureNameFromX = textureNameFromX;
        mTextureNameFromY = textureNameFromY;
        mTextureNameFromZ = textureNameFromZ;
    }

    //-----------------------------------------------------------------------
    const String& TriplanarTexturingFactory::getType() const
    {
        return TriplanarTexturing::type;
    }

    //-----------------------------------------------------------------------
    SubRenderState*	TriplanarTexturingFactory::createInstance(ScriptCompiler* compiler,
                                                       PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)
    {

        if (prop->name == "triplanarTexturing")
        {
            if (prop->values.size() == 6)
            {
                SubRenderState* subRenderState = createOrRetrieveInstance(translator);
                TriplanarTexturing* tpSubRenderState = static_cast<TriplanarTexturing*>(subRenderState);
                float parameters[3];
                AbstractNodeList::const_iterator it = prop->values.begin();
                if (false == SGScriptTranslator::getFloat(*it, parameters))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getFloat(*it, parameters + 1))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getFloat(*it, parameters + 2))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                Vector3 vParameters(parameters[0], parameters[1], parameters[2]);
                tpSubRenderState->setParameters(vParameters);

                String textureNameFromX, textureNameFromY, textureNameFromZ;
                it++;
                if (false == SGScriptTranslator::getString(*it, &textureNameFromX))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getString(*it, &textureNameFromY))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                it++;
                if (false == SGScriptTranslator::getString(*it, &textureNameFromZ))
                {
                    compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
                    return NULL;
                }
                tpSubRenderState->setTextureNames(textureNameFromX, textureNameFromY, textureNameFromZ);

                return subRenderState;
            }
            else
            {
                compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);
            }
        }

        return NULL;
    }

    //-----------------------------------------------------------------------
    SubRenderState*	TriplanarTexturingFactory::createInstanceImpl()
    {
        return OGRE_NEW TriplanarTexturing;
    }

}
}

#endif
<|endoftext|>