<commit_before>/*************************************************************************
 *
 *  $RCSfile: linkmgr2.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 20:45:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "linkmgr.hxx"

#include <vcl/msgbox.hxx>
#include "lnkbase.hxx"
//#include "linksrc.hxx"
#include "impldde.hxx"
//#include "svuidlg.hrc"
//#include "iface.hxx"

#include "app.hrc"
#include "sfxresid.hxx"

#pragma hdrstop

#define _SVSTDARR_STRINGSDTOR

#include <svtools/svstdarr.hxx>

namespace sfx2
{

SV_IMPL_PTRARR( SvBaseLinks, SvBaseLinkRefPtr )

SvLinkManager::SvLinkManager()
    : pPersist( 0 )
{
}

SvLinkManager::~SvLinkManager()
{
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( (*ppRef)->Is() )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->pLinkMgr = 0;
        }
        delete *ppRef;
    }
}

/************************************************************************
|*    SvLinkManager::Remove()
|*
|*    Beschreibung
*************************************************************************/

void SvLinkManager::Remove( SvBaseLink *pLink )
{
    // keine Links doppelt einfuegen
    int bFound = FALSE;
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( pLink == *(*ppRef) )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->pLinkMgr = 0;
            (*(*ppRef)).Clear();
            bFound = TRUE;
        }

        // falls noch leere rum stehen sollten, weg damit
        if( !(*ppRef)->Is() )
        {
            delete *ppRef;
            aLinkTbl.Remove( aLinkTbl.Count() - n, 1 );
            if( bFound )
                return ;
            --ppRef;
        }
    }
}

void SvLinkManager::Remove( USHORT nPos, USHORT nCnt )
{
    if( nCnt && nPos < aLinkTbl.Count() )
    {
        if( nPos + nCnt > aLinkTbl.Count() )
            nCnt = aLinkTbl.Count() - nPos;

        SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData() + nPos;
        for( USHORT n = nCnt; n; --n, ++ppRef )
        {
            if( (*ppRef)->Is() )
            {
                (*(*ppRef))->Disconnect();
                (*(*ppRef))->pLinkMgr = 0;
            }
            delete *ppRef;
        }
        aLinkTbl.Remove( nPos, nCnt );
    }
}

BOOL SvLinkManager::Insert( SvBaseLink* pLink )
{
    // keine Links doppelt einfuegen
    for( USHORT n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLinkRef* pTmp = aLinkTbl[ n ];
        if( !pTmp->Is() )
            aLinkTbl.DeleteAndDestroy( n-- );

        if( pLink == *pTmp )
            return FALSE;
    }

    SvBaseLinkRef* pTmp = new SvBaseLinkRef( pLink );
    pLink->pLinkMgr = this;
    aLinkTbl.Insert( pTmp, aLinkTbl.Count() );
    return TRUE;
}

BOOL SvLinkManager::InsertLink( SvBaseLink * pLink,
                                USHORT nObjType,
                                USHORT nUpdateMode,
                                const String* pName )
{
    // unbedingt zuerst
    pLink->SetObjType( nObjType );
    if( pName )
        pLink->SetName( *pName );
    pLink->SetUpdateMode( nUpdateMode );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink,
                                    const String& rServer,
                                    const String& rTopic,
                                    const String& rItem )
{
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    String sCmd;
    ::sfx2::MakeLnkName( sCmd, &rServer, rTopic, rItem );

    pLink->SetObjType( OBJECT_CLIENT_DDE );
    pLink->SetName( sCmd );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink )
{
    DBG_ASSERT( OBJECT_CLIENT_SO & pLink->GetObjType(), "no OBJECT_CLIENT_SO" )
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    if( pLink->GetObjType() == OBJECT_CLIENT_SO )
        pLink->SetObjType( OBJECT_CLIENT_DDE );

    return Insert( pLink );
}

// erfrage die Strings fuer den Dialog
BOOL SvLinkManager::GetDisplayNames( const SvBaseLink * pLink,
                                        String* pType,
                                        String* pFile,
                                        String* pLinkStr,
                                        String* pFilter ) const
{
    BOOL bRet = FALSE;
    String aLN = pLink->GetLinkSourceName();
    if( aLN.Len() != 0 && pLink->GetObjType() == OBJECT_CLIENT_DDE )
    {
        USHORT nTmp = 0;
        String sCmd( aLN );
        String sServer( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
        String sTopic( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );

        if( pType )
            *pType = sServer;
        if( pFile )
            *pFile = sTopic;
        if( pLinkStr )
            *pLinkStr = sCmd.Copy( nTmp );
        bRet = TRUE;
    }
    return bRet;
}

void SvLinkManager::UpdateAllLinks( BOOL bAskUpdate, BOOL bCallErrHdl,
                                    BOOL bUpdateGrfLinks, Window* pParentWin )
{
    SvStringsDtor aApps, aTopics, aItems;
    String sApp, sTopic, sItem;

    // erstmal eine Kopie vom Array machen, damit sich updatende Links in
    // Links in ... nicht dazwischen funken!!
    SvPtrarr aTmpArr( 255, 50 );
    USHORT n;
    for( n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLink* pLink = *aLinkTbl[ n ];
        if( !pLink )
        {
            Remove( n-- );
            continue;
        }
        aTmpArr.Insert( pLink, aTmpArr.Count() );
    }

    for( n = 0; n < aTmpArr.Count(); ++n )
    {
        SvBaseLink* pLink = (SvBaseLink*)aTmpArr[ n ];

        // suche erstmal im Array nach dem Eintrag
        USHORT nFndPos = USHRT_MAX;
        for( USHORT i = 0; i < aLinkTbl.Count(); ++i )
            if( pLink == *aLinkTbl[ i ] )
            {
                nFndPos = i;
                break;
            }

        if( USHRT_MAX == nFndPos )
            continue;                   // war noch nicht vorhanden!

        // Graphic-Links noch nicht updaten
        if( !pLink->IsVisible() ||
            ( !bUpdateGrfLinks && OBJECT_CLIENT_GRF == pLink->GetObjType() ))
            continue;

        if( bAskUpdate )
        {
            int nRet = QueryBox( pParentWin, WB_YES_NO | WB_DEF_YES, SfxResId( STR_QUERY_UPDATE_LINKS ) ).Execute();
            if( RET_YES != nRet )
                return ;        // es soll nichts geupdatet werden
            bAskUpdate = FALSE;     // einmal reicht
        }

        pLink->Update();
    }
}

/************************************************************************
|*    SvBaseLink::CreateObject()
|*
|*    Beschreibung
*************************************************************************/

SvLinkSourceRef SvLinkManager::CreateObj( SvBaseLink * pLink )
{
    if( OBJECT_CLIENT_DDE == pLink->GetObjType() )
        return new SvDDEObject();
    return SvLinkSourceRef();
}

BOOL SvLinkManager::InsertServer( SvLinkSource* pObj )
{
    // keine doppelt einfuegen
    if( !pObj || USHRT_MAX != aServerTbl.GetPos( pObj ) )
        return FALSE;

    aServerTbl.Insert( pObj, aServerTbl.Count() );
    return TRUE;
}

void SvLinkManager::RemoveServer( SvLinkSource* pObj )
{
    USHORT nPos = aServerTbl.GetPos( pObj );
    if( USHRT_MAX != nPos )
        aServerTbl.Remove( nPos, 1 );
}

void MakeLnkName( String& rName, const String* pType, const String& rFile,
                    const String& rLink, const String* pFilter )
{
    if( pType )
        (rName = *pType).EraseLeadingChars().EraseTrailingChars() += cTokenSeperator;
    else if( rName.Len() )
        rName.Erase();

    ((rName += rFile).EraseLeadingChars().EraseTrailingChars() +=
        cTokenSeperator ).EraseLeadingChars().EraseTrailingChars() += rLink;
    if( pFilter )
        ((rName += cTokenSeperator ) += *pFilter).EraseLeadingChars().EraseTrailingChars();
}

}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.434); FILE MERGED 2005/09/05 15:22:09 rt 1.2.434.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: linkmgr2.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:42:04 $
 *
 *  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 _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "linkmgr.hxx"

#include <vcl/msgbox.hxx>
#include "lnkbase.hxx"
//#include "linksrc.hxx"
#include "impldde.hxx"
//#include "svuidlg.hrc"
//#include "iface.hxx"

#include "app.hrc"
#include "sfxresid.hxx"

#pragma hdrstop

#define _SVSTDARR_STRINGSDTOR

#include <svtools/svstdarr.hxx>

namespace sfx2
{

SV_IMPL_PTRARR( SvBaseLinks, SvBaseLinkRefPtr )

SvLinkManager::SvLinkManager()
    : pPersist( 0 )
{
}

SvLinkManager::~SvLinkManager()
{
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( (*ppRef)->Is() )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->pLinkMgr = 0;
        }
        delete *ppRef;
    }
}

/************************************************************************
|*    SvLinkManager::Remove()
|*
|*    Beschreibung
*************************************************************************/

void SvLinkManager::Remove( SvBaseLink *pLink )
{
    // keine Links doppelt einfuegen
    int bFound = FALSE;
    SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData();
    for( USHORT n = aLinkTbl.Count(); n; --n, ++ppRef )
    {
        if( pLink == *(*ppRef) )
        {
            (*(*ppRef))->Disconnect();
            (*(*ppRef))->pLinkMgr = 0;
            (*(*ppRef)).Clear();
            bFound = TRUE;
        }

        // falls noch leere rum stehen sollten, weg damit
        if( !(*ppRef)->Is() )
        {
            delete *ppRef;
            aLinkTbl.Remove( aLinkTbl.Count() - n, 1 );
            if( bFound )
                return ;
            --ppRef;
        }
    }
}

void SvLinkManager::Remove( USHORT nPos, USHORT nCnt )
{
    if( nCnt && nPos < aLinkTbl.Count() )
    {
        if( nPos + nCnt > aLinkTbl.Count() )
            nCnt = aLinkTbl.Count() - nPos;

        SvBaseLinkRef** ppRef = (SvBaseLinkRef**)aLinkTbl.GetData() + nPos;
        for( USHORT n = nCnt; n; --n, ++ppRef )
        {
            if( (*ppRef)->Is() )
            {
                (*(*ppRef))->Disconnect();
                (*(*ppRef))->pLinkMgr = 0;
            }
            delete *ppRef;
        }
        aLinkTbl.Remove( nPos, nCnt );
    }
}

BOOL SvLinkManager::Insert( SvBaseLink* pLink )
{
    // keine Links doppelt einfuegen
    for( USHORT n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLinkRef* pTmp = aLinkTbl[ n ];
        if( !pTmp->Is() )
            aLinkTbl.DeleteAndDestroy( n-- );

        if( pLink == *pTmp )
            return FALSE;
    }

    SvBaseLinkRef* pTmp = new SvBaseLinkRef( pLink );
    pLink->pLinkMgr = this;
    aLinkTbl.Insert( pTmp, aLinkTbl.Count() );
    return TRUE;
}

BOOL SvLinkManager::InsertLink( SvBaseLink * pLink,
                                USHORT nObjType,
                                USHORT nUpdateMode,
                                const String* pName )
{
    // unbedingt zuerst
    pLink->SetObjType( nObjType );
    if( pName )
        pLink->SetName( *pName );
    pLink->SetUpdateMode( nUpdateMode );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink,
                                    const String& rServer,
                                    const String& rTopic,
                                    const String& rItem )
{
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    String sCmd;
    ::sfx2::MakeLnkName( sCmd, &rServer, rTopic, rItem );

    pLink->SetObjType( OBJECT_CLIENT_DDE );
    pLink->SetName( sCmd );
    return Insert( pLink );
}

BOOL SvLinkManager::InsertDDELink( SvBaseLink * pLink )
{
    DBG_ASSERT( OBJECT_CLIENT_SO & pLink->GetObjType(), "no OBJECT_CLIENT_SO" )
    if( !( OBJECT_CLIENT_SO & pLink->GetObjType() ) )
        return FALSE;

    if( pLink->GetObjType() == OBJECT_CLIENT_SO )
        pLink->SetObjType( OBJECT_CLIENT_DDE );

    return Insert( pLink );
}

// erfrage die Strings fuer den Dialog
BOOL SvLinkManager::GetDisplayNames( const SvBaseLink * pLink,
                                        String* pType,
                                        String* pFile,
                                        String* pLinkStr,
                                        String* pFilter ) const
{
    BOOL bRet = FALSE;
    String aLN = pLink->GetLinkSourceName();
    if( aLN.Len() != 0 && pLink->GetObjType() == OBJECT_CLIENT_DDE )
    {
        USHORT nTmp = 0;
        String sCmd( aLN );
        String sServer( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );
        String sTopic( sCmd.GetToken( 0, cTokenSeperator, nTmp ) );

        if( pType )
            *pType = sServer;
        if( pFile )
            *pFile = sTopic;
        if( pLinkStr )
            *pLinkStr = sCmd.Copy( nTmp );
        bRet = TRUE;
    }
    return bRet;
}

void SvLinkManager::UpdateAllLinks( BOOL bAskUpdate, BOOL bCallErrHdl,
                                    BOOL bUpdateGrfLinks, Window* pParentWin )
{
    SvStringsDtor aApps, aTopics, aItems;
    String sApp, sTopic, sItem;

    // erstmal eine Kopie vom Array machen, damit sich updatende Links in
    // Links in ... nicht dazwischen funken!!
    SvPtrarr aTmpArr( 255, 50 );
    USHORT n;
    for( n = 0; n < aLinkTbl.Count(); ++n )
    {
        SvBaseLink* pLink = *aLinkTbl[ n ];
        if( !pLink )
        {
            Remove( n-- );
            continue;
        }
        aTmpArr.Insert( pLink, aTmpArr.Count() );
    }

    for( n = 0; n < aTmpArr.Count(); ++n )
    {
        SvBaseLink* pLink = (SvBaseLink*)aTmpArr[ n ];

        // suche erstmal im Array nach dem Eintrag
        USHORT nFndPos = USHRT_MAX;
        for( USHORT i = 0; i < aLinkTbl.Count(); ++i )
            if( pLink == *aLinkTbl[ i ] )
            {
                nFndPos = i;
                break;
            }

        if( USHRT_MAX == nFndPos )
            continue;                   // war noch nicht vorhanden!

        // Graphic-Links noch nicht updaten
        if( !pLink->IsVisible() ||
            ( !bUpdateGrfLinks && OBJECT_CLIENT_GRF == pLink->GetObjType() ))
            continue;

        if( bAskUpdate )
        {
            int nRet = QueryBox( pParentWin, WB_YES_NO | WB_DEF_YES, SfxResId( STR_QUERY_UPDATE_LINKS ) ).Execute();
            if( RET_YES != nRet )
                return ;        // es soll nichts geupdatet werden
            bAskUpdate = FALSE;     // einmal reicht
        }

        pLink->Update();
    }
}

/************************************************************************
|*    SvBaseLink::CreateObject()
|*
|*    Beschreibung
*************************************************************************/

SvLinkSourceRef SvLinkManager::CreateObj( SvBaseLink * pLink )
{
    if( OBJECT_CLIENT_DDE == pLink->GetObjType() )
        return new SvDDEObject();
    return SvLinkSourceRef();
}

BOOL SvLinkManager::InsertServer( SvLinkSource* pObj )
{
    // keine doppelt einfuegen
    if( !pObj || USHRT_MAX != aServerTbl.GetPos( pObj ) )
        return FALSE;

    aServerTbl.Insert( pObj, aServerTbl.Count() );
    return TRUE;
}

void SvLinkManager::RemoveServer( SvLinkSource* pObj )
{
    USHORT nPos = aServerTbl.GetPos( pObj );
    if( USHRT_MAX != nPos )
        aServerTbl.Remove( nPos, 1 );
}

void MakeLnkName( String& rName, const String* pType, const String& rFile,
                    const String& rLink, const String* pFilter )
{
    if( pType )
        (rName = *pType).EraseLeadingChars().EraseTrailingChars() += cTokenSeperator;
    else if( rName.Len() )
        rName.Erase();

    ((rName += rFile).EraseLeadingChars().EraseTrailingChars() +=
        cTokenSeperator ).EraseLeadingChars().EraseTrailingChars() += rLink;
    if( pFilter )
        ((rName += cTokenSeperator ) += *pFilter).EraseLeadingChars().EraseTrailingChars();
}

}

<|endoftext|>


<commit_before>#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "floatMul.h"
#include "featureSupport.h"
#include <string>
#include <iostream>
#include <iomanip>
#ifdef HAVE_CUDA
// CUDA includes
#include <cuda_runtime.h>
#endif // HAVE_CUDA

cv::VideoCapture capture;
const char windowName[]  = "demo";
const char header[] = "precision: ";
const char* imagePath[][2] = {
	{ "defaultMaskHalf.png", "defaultMaskFloat.png"},
	{ "lenaMaskHalf.png",    "lenaMaskFloat.png"},
};
short *gainCuda = NULL;
float *gainFloatCuda = NULL;
unsigned char *imageCuda = NULL;
unsigned char *imageResult = NULL;

enum precision
{
	precisionHalf,
	precisionFloat,
};
enum device
{
	useCpuSimd,
	useGpu,
};

void computeStatistics(double time, char key)
{
	const int cHistoryMax = 16;
	static double history[cHistoryMax];
	static double square [cHistoryMax];
	static int iHistory = 0;
	switch (key)
	{
	case 'h':
	case 'H':
	case 'f':
	case 'F':
	case 'c':
	case 'C':
	case 'g':
	case 'G':
		for (int i = 0; i < cHistoryMax; i++)
		{
			history[i] = 0.0f;
			square[i] = 0.0f;
			iHistory = 0;
		}
		break;
	}

	history[iHistory] = time;
	square[iHistory]  = time * time;

	double sum = 0.0f;
	double squareSum = 0.0f;
	for (int i = 0; i < cHistoryMax; i++)
	{
		sum += history[i];
		squareSum += square[i];
	}
	double average = sum / (double)cHistoryMax;
	squareSum /= cHistoryMax;
	double variance = squareSum - (average * average);
	std::cout << "average: " << std::fixed << std::setprecision(3) << average * 1000.0f << "[ms] ";
	std::cout << "stddev: "  << std::fixed << std::setprecision(3) << sqrt(variance) * 1000.0f << "[ms]  \r";
	std::cout << std::flush;

	iHistory++;
	iHistory = iHistory & (cHistoryMax-1);
}

#ifdef HAVE_CUDA
extern "C" void
launchCudaProcessHalf(dim3 grid, dim3 block, int sbytes,
						short *gain,
						unsigned char *imageInput,
						unsigned char *imageOutput,
						int imgw);

extern "C" void
launchCudaProcessFloat(dim3 grid, dim3 block, int sbytes,
						float *gain,
						unsigned char *imageInput,
						unsigned char *imageOutput,
						int imgw);

double multiplyImageCuda(cv::Mat &image, cv::Mat gain)
{
	unsigned int image_width  = image.cols;
	unsigned int image_height = image.rows;

	cudaMemcpy(imageCuda, image.data, image_height*image_width*sizeof(char)*3, cudaMemcpyHostToDevice);

	// calculate grid size
    dim3 block(16, 16, 1);
    dim3 grid(image_width / block.x, image_height / block.y, 1);
	int64 begin, end;

	switch (gain.elemSize())
	{
	case 2:
		begin = cv::getTickCount();
		cudaMemcpy(gainCuda,  gain.data,  image_height*image_width*sizeof(short),  cudaMemcpyHostToDevice);
		end = cv::getTickCount();
		launchCudaProcessHalf(grid, block, 0, gainCuda, imageCuda, imageResult, image_width);
		break;
	case 4:
		begin = cv::getTickCount();
		cudaMemcpy(gainFloatCuda,  gain.data,  image_height*image_width*sizeof(float),  cudaMemcpyHostToDevice);
		end = cv::getTickCount();
		launchCudaProcessFloat(grid, block, 0, gainFloatCuda, imageCuda, imageResult, image_width);
		break;
	}
	cudaMemcpy(image.data, imageResult, image_height*image_width*sizeof(char)*3, cudaMemcpyDeviceToHost);

	double tickCountElapsed = double(end - begin);
	return tickCountElapsed/(double)cv::getTickFrequency();
}
#endif // HAVE_CUDA

double multiplyImage(cv::Mat &image, cv::Mat gain)
{
	cv::Mat stub, b, g, r;
	std::vector<cv::Mat> arrayColor;
	arrayColor.push_back(b);
	arrayColor.push_back(g);
	arrayColor.push_back(r);
	cv::split(image, arrayColor);
	int64 begin, end;

	begin = cv::getTickCount();
	switch (gain.elemSize())
	{
	case 2:
		for (unsigned int i = 0; i < arrayColor.size(); i++)
		{
			multiply(arrayColor[i].data, (short*)gain.data, arrayColor[i].data, arrayColor[i].rows*arrayColor[i].cols);
		}
		break;
	case 4:
	default:
		for (unsigned int i = 0; i < arrayColor.size(); i++)
		{
			arrayColor[i].convertTo(stub, CV_32FC1);
			multiply(stub, gain, arrayColor[i], 1.0, CV_8UC1);
		}
		break;
	}
	end = cv::getTickCount();
	cv::merge(arrayColor, image);

	double tickCountElapsed = double(end - begin);
	return tickCountElapsed/(double)cv::getTickFrequency();
}

bool isFinish(char key)
{
	bool finishKey = false;
	switch (key)
	{
	case 'q':
	case 'Q':
	case 27: // ESC key
		finishKey = true;
	default:
		break;
	}
	return finishKey;
}

#ifdef HAVE_CUDA
void initArray(cv::Mat &image)
{
	unsigned int w = image.cols;
	unsigned int h = image.rows;
	unsigned int s = w * h;
	cudaMalloc((short**)&gainCuda, (s*sizeof(short)));
	cudaMalloc((float**)&gainFloatCuda, (s*sizeof(float)));
	cudaMalloc((unsigned char**)&imageCuda, (s*sizeof(unsigned char)*3));
	cudaMalloc((unsigned char**)&imageResult, (s*sizeof(unsigned char)*3));
}

void releaseArray()
{
	cudaFree((void*)gainCuda);
	cudaFree((void*)gainFloatCuda);
	cudaFree((void*)imageCuda);
	cudaFree((void*)imageResult);
}

bool initCuda()
{
	int devID = 0;
	int device_count= 0;

	cudaGetDeviceCount(&device_count);

	if (device_count < 1)
	{
		return false;
	}

	cudaSetDevice(devID);

	return true;
}
#else
void initArray(cv::Mat &image){}
void releaseArray(){}
bool initCuda(){ return false; }
#endif // HAVE_CUDA

int main(int argc, char**argv)
{
	capture.open(0);
	cv::Mat image;
	capture >> image;

	cv::namedWindow(windowName);
	cv::imshow(windowName, image);

	initCuda();
	initArray(image);

	char key = -1;
	enum device statusDevice = useCpuSimd;
	enum precision statusPrecision = precisionFloat;
	int index = 1;
	cv::Mat stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
	cv::Mat gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
	double elapsedTime;
	while (isFinish(key) == false)
	{
		capture >> image;

		switch (key)
		{
		case 'h':
		case 'H':
			// switch to half precision
			statusPrecision = precisionHalf;
			std::cout << std::endl << header << "half  " << std::endl;
			stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
			gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
			break;
		case 'f':
		case 'F':
			// switch to single precision
			statusPrecision = precisionFloat;
			std::cout << std::endl << header << "single" << std::endl;
			stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
			gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
			break;
		case '0':
		case '1':
			index = key - '0';
			if (statusPrecision == precisionHalf)
			{
				// precision half
				stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
				gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
			}
			else
			{
				// precision single
				stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
				gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
			}
			break;
		case 'c':
		case 'C':
			std::cout << std::endl << "Using CPU SIMD           " << std::endl;
			statusDevice = useCpuSimd;
			break;
		case 'g':
		case 'G':
			std::cout << std::endl << "Using GPU                " << std::endl;
			statusDevice = useGpu;
			break;
		default:
			break;
		}

		if (statusDevice == useCpuSimd)
		{
			elapsedTime = multiplyImage(image, gain);
		}
		else
		{
#ifdef HAVE_CUDA
			// CUDA
			elapsedTime = multiplyImageCuda(image, gain);
#endif // HAVE_CUDA
		}
		computeStatistics(elapsedTime, key);

		cv::imshow(windowName, image);
		key = cv::waitKey(1);
	}
	std::cout << std::endl;
	cv::destroyAllWindows();
	releaseArray();

	return 0;
}
<commit_msg>save image when 's' key pressed<commit_after>#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "floatMul.h"
#include "featureSupport.h"
#include <string>
#include <iostream>
#include <iomanip>
#ifdef HAVE_CUDA
// CUDA includes
#include <cuda_runtime.h>
#endif // HAVE_CUDA

cv::VideoCapture capture;
const char dumpFilename[] = "dump.png";
const char windowName[]  = "demo";
const char header[] = "precision: ";
const char* imagePath[][2] = {
	{ "defaultMaskHalf.png", "defaultMaskFloat.png"},
	{ "lenaMaskHalf.png",    "lenaMaskFloat.png"},
};
short *gainCuda = NULL;
float *gainFloatCuda = NULL;
unsigned char *imageCuda = NULL;
unsigned char *imageResult = NULL;

enum precision
{
	precisionHalf,
	precisionFloat,
};
enum device
{
	useCpuSimd,
	useGpu,
};

void computeStatistics(double time, char key)
{
	const int cHistoryMax = 16;
	static double history[cHistoryMax];
	static double square [cHistoryMax];
	static int iHistory = 0;
	switch (key)
	{
	case 'h':
	case 'H':
	case 'f':
	case 'F':
	case 'c':
	case 'C':
	case 'g':
	case 'G':
		for (int i = 0; i < cHistoryMax; i++)
		{
			history[i] = 0.0f;
			square[i] = 0.0f;
			iHistory = 0;
		}
		break;
	}

	history[iHistory] = time;
	square[iHistory]  = time * time;

	double sum = 0.0f;
	double squareSum = 0.0f;
	for (int i = 0; i < cHistoryMax; i++)
	{
		sum += history[i];
		squareSum += square[i];
	}
	double average = sum / (double)cHistoryMax;
	squareSum /= cHistoryMax;
	double variance = squareSum - (average * average);
	std::cout << "average: " << std::fixed << std::setprecision(3) << average * 1000.0f << "[ms] ";
	std::cout << "stddev: "  << std::fixed << std::setprecision(3) << sqrt(variance) * 1000.0f << "[ms]  \r";
	std::cout << std::flush;

	iHistory++;
	iHistory = iHistory & (cHistoryMax-1);
}

#ifdef HAVE_CUDA
extern "C" void
launchCudaProcessHalf(dim3 grid, dim3 block, int sbytes,
						short *gain,
						unsigned char *imageInput,
						unsigned char *imageOutput,
						int imgw);

extern "C" void
launchCudaProcessFloat(dim3 grid, dim3 block, int sbytes,
						float *gain,
						unsigned char *imageInput,
						unsigned char *imageOutput,
						int imgw);

double multiplyImageCuda(cv::Mat &image, cv::Mat gain)
{
	unsigned int image_width  = image.cols;
	unsigned int image_height = image.rows;

	cudaMemcpy(imageCuda, image.data, image_height*image_width*sizeof(char)*3, cudaMemcpyHostToDevice);

	// calculate grid size
    dim3 block(16, 16, 1);
    dim3 grid(image_width / block.x, image_height / block.y, 1);
	int64 begin, end;

	switch (gain.elemSize())
	{
	case 2:
		begin = cv::getTickCount();
		cudaMemcpy(gainCuda,  gain.data,  image_height*image_width*sizeof(short),  cudaMemcpyHostToDevice);
		end = cv::getTickCount();
		launchCudaProcessHalf(grid, block, 0, gainCuda, imageCuda, imageResult, image_width);
		break;
	case 4:
		begin = cv::getTickCount();
		cudaMemcpy(gainFloatCuda,  gain.data,  image_height*image_width*sizeof(float),  cudaMemcpyHostToDevice);
		end = cv::getTickCount();
		launchCudaProcessFloat(grid, block, 0, gainFloatCuda, imageCuda, imageResult, image_width);
		break;
	}
	cudaMemcpy(image.data, imageResult, image_height*image_width*sizeof(char)*3, cudaMemcpyDeviceToHost);

	double tickCountElapsed = double(end - begin);
	return tickCountElapsed/(double)cv::getTickFrequency();
}
#endif // HAVE_CUDA

double multiplyImage(cv::Mat &image, cv::Mat gain)
{
	cv::Mat stub, b, g, r;
	std::vector<cv::Mat> arrayColor;
	arrayColor.push_back(b);
	arrayColor.push_back(g);
	arrayColor.push_back(r);
	cv::split(image, arrayColor);
	int64 begin, end;

	begin = cv::getTickCount();
	switch (gain.elemSize())
	{
	case 2:
		for (unsigned int i = 0; i < arrayColor.size(); i++)
		{
			multiply(arrayColor[i].data, (short*)gain.data, arrayColor[i].data, arrayColor[i].rows*arrayColor[i].cols);
		}
		break;
	case 4:
	default:
		for (unsigned int i = 0; i < arrayColor.size(); i++)
		{
			arrayColor[i].convertTo(stub, CV_32FC1);
			multiply(stub, gain, arrayColor[i], 1.0, CV_8UC1);
		}
		break;
	}
	end = cv::getTickCount();
	cv::merge(arrayColor, image);

	double tickCountElapsed = double(end - begin);
	return tickCountElapsed/(double)cv::getTickFrequency();
}

bool isFinish(char key)
{
	bool finishKey = false;
	switch (key)
	{
	case 'q':
	case 'Q':
	case 27: // ESC key
		finishKey = true;
	default:
		break;
	}
	return finishKey;
}

#ifdef HAVE_CUDA
void initArray(cv::Mat &image)
{
	unsigned int w = image.cols;
	unsigned int h = image.rows;
	unsigned int s = w * h;
	cudaMalloc((short**)&gainCuda, (s*sizeof(short)));
	cudaMalloc((float**)&gainFloatCuda, (s*sizeof(float)));
	cudaMalloc((unsigned char**)&imageCuda, (s*sizeof(unsigned char)*3));
	cudaMalloc((unsigned char**)&imageResult, (s*sizeof(unsigned char)*3));
}

void releaseArray()
{
	cudaFree((void*)gainCuda);
	cudaFree((void*)gainFloatCuda);
	cudaFree((void*)imageCuda);
	cudaFree((void*)imageResult);
}

bool initCuda()
{
	int devID = 0;
	int device_count= 0;

	cudaGetDeviceCount(&device_count);

	if (device_count < 1)
	{
		return false;
	}

	cudaSetDevice(devID);

	return true;
}
#else
void initArray(cv::Mat &image){}
void releaseArray(){}
bool initCuda(){ return false; }
#endif // HAVE_CUDA

int main(int argc, char**argv)
{
	capture.open(0);
	cv::Mat image;
	capture >> image;

	cv::namedWindow(windowName);
	cv::imshow(windowName, image);

	initCuda();
	initArray(image);

	char key = -1;
	enum device statusDevice = useCpuSimd;
	enum precision statusPrecision = precisionFloat;
	int index = 1;
	cv::Mat stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
	cv::Mat gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
	double elapsedTime;
	while (isFinish(key) == false)
	{
		capture >> image;

		switch (key)
		{
		case 'h':
		case 'H':
			// switch to half precision
			statusPrecision = precisionHalf;
			std::cout << std::endl << header << "half  " << std::endl;
			stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
			gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
			break;
		case 'f':
		case 'F':
			// switch to single precision
			statusPrecision = precisionFloat;
			std::cout << std::endl << header << "single" << std::endl;
			stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
			gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
			break;
		case '0':
		case '1':
			index = key - '0';
			if (statusPrecision == precisionHalf)
			{
				// precision half
				stub = cv::imread(imagePath[index][0], cv::IMREAD_UNCHANGED);
				gain = cv::Mat(stub.rows, stub.cols/2, CV_16SC1, stub.data);
			}
			else
			{
				// precision single
				stub = cv::imread(imagePath[index][1], cv::IMREAD_UNCHANGED);
				gain = cv::Mat(stub.rows, stub.cols, CV_32FC1, stub.data);
			}
			break;
		case 'c':
		case 'C':
			std::cout << std::endl << "Using CPU SIMD           " << std::endl;
			statusDevice = useCpuSimd;
			break;
		case 'g':
		case 'G':
			std::cout << std::endl << "Using GPU                " << std::endl;
			statusDevice = useGpu;
			break;
		default:
			break;
		}

		if (statusDevice == useCpuSimd)
		{
			elapsedTime = multiplyImage(image, gain);
		}
		else
		{
#ifdef HAVE_CUDA
			// CUDA
			elapsedTime = multiplyImageCuda(image, gain);
#endif // HAVE_CUDA
		}
		computeStatistics(elapsedTime, key);

		if (key == 's' || key == 'S')
		{
			cv::imwrite(dumpFilename, image);
		}

		cv::imshow(windowName, image);
		key = cv::waitKey(1);
	}
	std::cout << std::endl;
	cv::destroyAllWindows();
	releaseArray();

	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/site_instance.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_type.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class RenderViewHostManagerTest : public InProcessBrowserTest {
 public:
  RenderViewHostManagerTest() {
    EnableDOMAutomation();
  }

  static bool GetFilePathWithHostAndPortReplacement(
      const std::string& original_file_path,
      const net::HostPortPair& host_port_pair,
      std::string* replacement_path) {
    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
    return net::TestServer::GetFilePathWithReplacements(
        original_file_path, replacement_text, replacement_path);
  }
};

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       SwapProcessWithRelNoreferrerAndTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer + target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_FALSE(browser()->GetSelectedTabContents()->render_manager()->
                   pending_render_view_host());

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyRelNoreferrer) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}

// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
// Started failing on Linux and Mac too, http://crbug.com/77762.
#define MAYBE_ChromeURLAfterDownload FLAKY_ChromeURLAfterDownload
#endif  // defined(OS_WIN)

// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       MAYBE_ChromeURLAfterDownload) {
  GURL downloads_url("chrome://downloads");
  GURL extensions_url("chrome://extensions");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  ui_test_utils::NavigateToURL(browser(), zip_url);
  ui_test_utils::WaitForDownloadCount(
      browser()->profile()->GetDownloadManager(), 1);
  ui_test_utils::NavigateToURL(browser(), extensions_url);

  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool webui_responded = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.domAutomationController.send(window.webui_responded_);",
      &webui_responded));
  EXPECT_TRUE(webui_responded);
}

class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
        Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::BROWSER_CLOSED:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

 private:
  NotificationRegistrar registrar_;
};

// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_BrowserCloseAfterDownload) {
  GURL downloads_url("chrome://downloads");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  ASSERT_TRUE(file_util::PathExists(zip_download));
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool result = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.onunload = function() { var do_nothing = 0; }; "
      L"window.domAutomationController.send(true);",
      &result));
  EXPECT_TRUE(result);
  ui_test_utils::NavigateToURL(browser(), zip_url);

  ui_test_utils::WaitForDownloadCount(
    browser()->profile()->GetDownloadManager(), 1);

  browser()->CloseWindow();
  BrowserClosedObserver wait_for_close(browser());
}

// Test for crbug.com/76666.  A cross-site navigation that fails with a 204
// error should not make us ignore future renderer-initiated navigations.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ClickLinkAfter204Error) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  // The links will point to the HTTPS server.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Load a cross-site page that fails with a 204 error.
  ui_test_utils::NavigateToURL(browser(), https_server.GetURL("nocontent"));

  // We should still be looking at the normal page.
  scoped_refptr<SiteInstance> post_nav_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, post_nav_site_instance);
  EXPECT_EQ("/files/click-noreferrer-links.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Renderer-initiated navigations should work.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}
<commit_msg>Revert 79680 - Mark ChromeURLAfterDownload as flaky.<commit_after>// Copyright (c) 2011 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 "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/path_service.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_error_reporter.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "content/browser/site_instance.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/notification_details.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_type.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"

class RenderViewHostManagerTest : public InProcessBrowserTest {
 public:
  RenderViewHostManagerTest() {
    EnableDOMAutomation();
  }

  static bool GetFilePathWithHostAndPortReplacement(
      const std::string& original_file_path,
      const net::HostPortPair& host_port_pair,
      std::string* replacement_path) {
    std::vector<net::TestServer::StringPair> replacement_text;
    replacement_text.push_back(
        make_pair("REPLACE_WITH_HOST_AND_PORT", host_port_pair.ToString()));
    return net::TestServer::GetFilePathWithReplacements(
        original_file_path, replacement_text, replacement_path);
  }
};

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and target=_blank should create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       SwapProcessWithRelNoreferrerAndTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer + target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_FALSE(browser()->GetSelectedTabContents()->render_manager()->
                   pending_render_view_host());

  // Should have a new SiteInstance.
  scoped_refptr<SiteInstance> noref_blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_NE(orig_site_instance, noref_blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with just
// target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyTargetBlank) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a target=blank link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickTargetBlankLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the tab to open.
  if (browser()->tab_count() < 2)
    ui_test_utils::WaitForNewTab(browser());

  // Opens in new tab.
  EXPECT_EQ(2, browser()->tab_count());
  EXPECT_EQ(1, browser()->selected_index());

  // Wait for the cross-site transition in the new tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> blank_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, blank_site_instance);
}

// Test for crbug.com/24447.  Following a cross-site link with rel=noreferrer
// and no target=_blank should not create a new SiteInstance.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DontSwapProcessWithOnlyRelNoreferrer) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Test clicking a rel=noreferrer link.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}

// Hangs flakily in Win, http://crbug.com/45040.
#if defined(OS_WIN)
#define MAYBE_ChromeURLAfterDownload DISABLED_ChromeURLAfterDownload
#else
#define MAYBE_ChromeURLAfterDownload ChromeURLAfterDownload
#endif  // defined(OS_WIN)

// Test for crbug.com/14505. This tests that chrome:// urls are still functional
// after download of a file while viewing another chrome://.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       MAYBE_ChromeURLAfterDownload) {
  GURL downloads_url("chrome://downloads");
  GURL extensions_url("chrome://extensions");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  ui_test_utils::NavigateToURL(browser(), zip_url);
  ui_test_utils::WaitForDownloadCount(
      browser()->profile()->GetDownloadManager(), 1);
  ui_test_utils::NavigateToURL(browser(), extensions_url);

  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool webui_responded = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.domAutomationController.send(window.webui_responded_);",
      &webui_responded));
  EXPECT_TRUE(webui_responded);
}

class BrowserClosedObserver : public NotificationObserver {
 public:
  explicit BrowserClosedObserver(Browser* browser) {
    registrar_.Add(this, NotificationType::BROWSER_CLOSED,
        Source<Browser>(browser));
    ui_test_utils::RunMessageLoop();
  }

  // NotificationObserver
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    switch (type.value) {
      case NotificationType::BROWSER_CLOSED:
        MessageLoopForUI::current()->Quit();
        break;
      default:
        NOTREACHED();
        break;
    }
  }

 private:
  NotificationRegistrar registrar_;
};

// Test for crbug.com/12745. This tests that if a download is initiated from
// a chrome:// page that has registered and onunload handler, the browser
// will be able to close.
// TODO(rafaelw): The fix for 12745 has now also been reverted. Another fix
// must be found before this can be re-enabled.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest,
                       DISABLED_BrowserCloseAfterDownload) {
  GURL downloads_url("chrome://downloads");
  FilePath zip_download;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &zip_download));
  zip_download = zip_download.AppendASCII("zip").AppendASCII("test.zip");
  ASSERT_TRUE(file_util::PathExists(zip_download));
  GURL zip_url = net::FilePathToFileURL(zip_download);

  ui_test_utils::NavigateToURL(browser(), downloads_url);
  TabContents *contents = browser()->GetSelectedTabContents();
  ASSERT_TRUE(contents);
  bool result = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      contents->render_view_host(),
      L"",
      L"window.onunload = function() { var do_nothing = 0; }; "
      L"window.domAutomationController.send(true);",
      &result));
  EXPECT_TRUE(result);
  ui_test_utils::NavigateToURL(browser(), zip_url);

  ui_test_utils::WaitForDownloadCount(
    browser()->profile()->GetDownloadManager(), 1);

  browser()->CloseWindow();
  BrowserClosedObserver wait_for_close(browser());
}

// Test for crbug.com/76666.  A cross-site navigation that fails with a 204
// error should not make us ignore future renderer-initiated navigations.
IN_PROC_BROWSER_TEST_F(RenderViewHostManagerTest, ClickLinkAfter204Error) {
  // Start two servers with different sites.
  ASSERT_TRUE(test_server()->Start());
  net::TestServer https_server(
      net::TestServer::TYPE_HTTPS,
      FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  // Load a page with links that open in a new window.
  // The links will point to the HTTPS server.
  std::string replacement_path;
  ASSERT_TRUE(GetFilePathWithHostAndPortReplacement(
      "files/click-noreferrer-links.html",
      https_server.host_port_pair(),
      &replacement_path));
  ui_test_utils::NavigateToURL(browser(),
                               test_server()->GetURL(replacement_path));

  // Get the original SiteInstance for later comparison.
  scoped_refptr<SiteInstance> orig_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_TRUE(orig_site_instance != NULL);

  // Load a cross-site page that fails with a 204 error.
  ui_test_utils::NavigateToURL(browser(), https_server.GetURL("nocontent"));

  // We should still be looking at the normal page.
  scoped_refptr<SiteInstance> post_nav_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, post_nav_site_instance);
  EXPECT_EQ("/files/click-noreferrer-links.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Renderer-initiated navigations should work.
  bool success = false;
  EXPECT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(
      browser()->GetSelectedTabContents()->render_view_host(), L"",
      L"window.domAutomationController.send(clickNoRefLink());",
      &success));
  EXPECT_TRUE(success);

  // Wait for the cross-site transition in the current tab to finish.
  ui_test_utils::WaitForLoadStop(browser()->GetSelectedTabContents());

  // Opens in same tab.
  EXPECT_EQ(1, browser()->tab_count());
  EXPECT_EQ(0, browser()->selected_index());
  EXPECT_EQ("/files/title2.html",
            browser()->GetSelectedTabContents()->GetURL().path());

  // Should have the same SiteInstance.
  scoped_refptr<SiteInstance> noref_site_instance(
      browser()->GetSelectedTabContents()->GetSiteInstance());
  EXPECT_EQ(orig_site_instance, noref_site_instance);
}
<|endoftext|>


<commit_before><commit_msg>SetFmtItemByAutoFmt/SetTxtFmtCollByAutoFmt called with SwTxtNode<commit_after><|endoftext|>


<commit_before>#include "lrate.h"
#include "tensor/momentum.h"
#include "text/json_writer.h"
#include "solver_stoch_adam.h"

using namespace nano;

solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0) const
{
        const auto beta1s = make_finite_space(scalar_t(0.900));
        const auto beta2s = make_finite_space(scalar_t(0.999));
        return tune(this, param, function, x0, make_alpha0s(), make_decays(), make_epsilons(), beta1s, beta2s);
}

solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0,
        const scalar_t alpha0, const scalar_t decay, const scalar_t epsilon, const scalar_t beta1, const scalar_t beta2)
{
        // learning rate schedule
        lrate_t lrate(alpha0, decay);

        // first-order momentum of the gradient
        momentum_t<vector_t> m(beta1, x0.size());

        // second-order momentum of the gradient
        momentum_t<vector_t> v(beta2, x0.size());

        // assembly the solver
        const auto solver = [&] (solver_state_t& cstate, const solver_state_t&)
        {
                // learning rate
                const scalar_t alpha = lrate.get();

                // descent direction
                m.update(cstate.g);
                v.update(cstate.g.array().square());

                cstate.d = -m.value().array() / (epsilon + v.value().array().sqrt());

                // update solution
                function.stoch_next();
                cstate.stoch_update(function, alpha);
        };

        const auto snapshot = [&] (const solver_state_t& cstate, solver_state_t& sstate)
        {
                sstate.update(function, cstate.x);
        };

        return  loop(param, function, x0, solver, snapshot,
                json_writer_t().object("alpha0", alpha0, "decay", decay, "epsilon", epsilon, "beta1", beta1, "beta2", beta2).str());
}
<commit_msg>use decay=0.50 for adam (like in the paper)<commit_after>#include "lrate.h"
#include "tensor/momentum.h"
#include "text/json_writer.h"
#include "solver_stoch_adam.h"

using namespace nano;

solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0) const
{
        const auto decays = make_finite_space(scalar_t(0.500));
        const auto beta1s = make_finite_space(scalar_t(0.900));
        const auto beta2s = make_finite_space(scalar_t(0.999));
        return tune(this, param, function, x0, make_alpha0s(), decays, make_epsilons(), beta1s, beta2s);
}

solver_state_t stoch_adam_t::minimize(const stoch_params_t& param, const function_t& function, const vector_t& x0,
        const scalar_t alpha0, const scalar_t decay, const scalar_t epsilon, const scalar_t beta1, const scalar_t beta2)
{
        // learning rate schedule
        lrate_t lrate(alpha0, decay);

        // first-order momentum of the gradient
        momentum_t<vector_t> m(beta1, x0.size());

        // second-order momentum of the gradient
        momentum_t<vector_t> v(beta2, x0.size());

        // assembly the solver
        const auto solver = [&] (solver_state_t& cstate, const solver_state_t&)
        {
                // learning rate
                const scalar_t alpha = lrate.get();

                // descent direction
                m.update(cstate.g);
                v.update(cstate.g.array().square());

                cstate.d = -m.value().array() / (epsilon + v.value().array().sqrt());

                // update solution
                function.stoch_next();
                cstate.stoch_update(function, alpha);
        };

        const auto snapshot = [&] (const solver_state_t& cstate, solver_state_t& sstate)
        {
                sstate.update(function, cstate.x);
        };

        return  loop(param, function, x0, solver, snapshot,
                json_writer_t().object("alpha0", alpha0, "decay", decay, "epsilon", epsilon, "beta1", beta1, "beta2", beta2).str());
}
<|endoftext|>


<commit_before>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "websearch_api_compat.h"
#include "cgi.h"
#include "urlmatch.h"
#include "mrf.h"

using namespace sp;
using lsh::mrf;

namespace seeks_plugins
{

  websearch_api_compat::websearch_api_compat()
    : plugin()
  {
    _name = "websearch-api-compat";
    _version_major = "0";
    _version_minor = "3";

    // cgi_dispatchers.
    cgi_dispatcher *cgid_wb_search
    = new cgi_dispatcher("search", &websearch_api_compat::cgi_search_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_search);

    cgi_dispatcher *cgid_wb_search_cache
    = new cgi_dispatcher("search_cache", &websearch_api_compat::cgi_search_cache_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_search_cache);

    cgi_dispatcher *cgid_wb_qc_redir
    = new cgi_dispatcher("qc_redir",&websearch_api_compat::cgi_qc_redir_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_qc_redir);

    cgi_dispatcher *cgid_wb_tbd
    = new cgi_dispatcher("tbd",&websearch_api_compat::cgi_tbd_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_tbd);
  }

  websearch_api_compat::~websearch_api_compat()
  {
  }

  sp_err websearch_api_compat::cgi_search_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;

        // check for action.
        const char *action = miscutil::lookup(parameters,"action");
        if (!action || strcasecmp(action,"expand")==0
            || strcasecmp(action,"page")==0)
          {
            // route to /search/txt
            free(csp->_http._path);
            std::string path = "/search/txt/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_search(csp,rsp,parameters);
          }
        else if (strcasecmp(action,"types")==0)
          {
            // route to /cluster/types
            free(csp->_http._path);
            std::string path = "/cluster/types/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_clustered_types(csp,rsp,parameters);
          }
        else if (strcasecmp(action,"clusterize")==0)
          {
            // route to /cluster/auto
            free(csp->_http._path);
            std::string path = "/cluster/auto/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_clusterize(csp,rsp,parameters);
          }
        else if (strcasecmp(action,"similarity")==0)
          {
            // route to /similar/txt
            free(csp->_http._path);
            std::string path = "/similar/txt/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_similarity(csp,rsp,parameters);
          }
        else return SP_ERR_CGI_PARAMS;
      }
    else return SP_ERR_CGI_PARAMS;
  }

  sp_err websearch_api_compat::cgi_search_cache_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;

        // check for url.
        const char *url_str = miscutil::lookup(parameters,"url");
        if (!url_str)
          return SP_ERR_CGI_PARAMS;
        std::string url = url_str;
        std::transform(url.begin(),url.end(),url.begin(),tolower);
        std::string surl = urlmatch::strip_url(url);
        uint32_t id = mrf::mrf_single_feature(surl);
        std::string sid = miscutil::to_string(id);

        // route to /cache
        free(csp->_http._path);
        std::string path = "/cache/txt/" + query + "/" + sid;
        csp->_http._path = strdup(path.c_str());
        return websearch::cgi_websearch_search_cache(csp,rsp,parameters);
      }
    else return SP_ERR_CGI_PARAMS;
  }

  sp_err websearch_api_compat::cgi_qc_redir_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;

        // redirection.
        miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>\
                                (parameters),"redirect",1,"1",1);

        // check for url.
        const char *url_str = miscutil::lookup(parameters,"url");
        if (!url_str)
          return SP_ERR_CGI_PARAMS;
        std::string url = url_str;
        std::transform(url.begin(),url.end(),url.begin(),tolower);
        std::string surl = urlmatch::strip_url(url);
        uint32_t id = mrf::mrf_single_feature(surl);
        std::string sid = miscutil::to_string(id);

        // route to POST /search/txt
        free(csp->_http._path);
        std::string path = "/search/txt/" + query + "/" + sid;
        csp->_http._path = strdup(path.c_str());
        free(csp->_http._gpc);
        csp->_http._gpc = strdup("post");
        return websearch::cgi_websearch_search(csp,rsp,parameters);
      }
    else return SP_ERR_CGI_PARAMS;
  }

  sp_err websearch_api_compat::cgi_tbd_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;

        // check for url.
        const char *url_str = miscutil::lookup(parameters,"url");
        if (!url_str)
          return SP_ERR_CGI_PARAMS;
        std::string url = url_str;
        std::transform(url.begin(),url.end(),url.begin(),tolower);
        std::string surl = urlmatch::strip_url(url);
        uint32_t id = mrf::mrf_single_feature(surl);
        std::string sid = miscutil::to_string(id);

        // route to DELETE /search/txt
        free(csp->_http._path);
        std::string path = "/search/txt/" + query + "/" + sid;
        csp->_http._path = strdup(path.c_str());
        free(csp->_http._gpc);
        csp->_http._gpc = strdup("delete");
        sp_err err = websearch::cgi_websearch_search(csp,rsp,parameters);
        if (err != SP_ERR_OK)
          return err;
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");
        miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"action",1,"expand",1);
        miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"output",1,"html",1);

        //return websearch_api_compat::cgi_search_compat(csp,rsp,parameters);
        free(csp->_http._gpc);
        csp->_http._gpc = strdup("get");
        free(csp->_http._path);
        path = "/search/txt/" + query;
        csp->_http._path = strdup(path.c_str());
        return websearch::cgi_websearch_search(csp,rsp,parameters);
      }
    else return SP_ERR_CGI_PARAMS;
  }

  /* plugin registration */
  extern "C"
  {
    plugin* maker()
    {
      return new websearch_api_compat;
    }
  }

} /* end of namespace. */
<commit_msg>fixed leak in websearch API compatibility plugin<commit_after>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2011 Emmanuel Benazera <ebenazer@seeks-project.info>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "websearch_api_compat.h"
#include "cgi.h"
#include "urlmatch.h"
#include "mrf.h"

using namespace sp;
using lsh::mrf;

namespace seeks_plugins
{

  websearch_api_compat::websearch_api_compat()
    : plugin()
  {
    _name = "websearch-api-compat";
    _version_major = "0";
    _version_minor = "3";

    // cgi_dispatchers.
    cgi_dispatcher *cgid_wb_search
    = new cgi_dispatcher("search", &websearch_api_compat::cgi_search_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_search);

    cgi_dispatcher *cgid_wb_search_cache
    = new cgi_dispatcher("search_cache", &websearch_api_compat::cgi_search_cache_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_search_cache);

    cgi_dispatcher *cgid_wb_qc_redir
    = new cgi_dispatcher("qc_redir",&websearch_api_compat::cgi_qc_redir_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_qc_redir);

    cgi_dispatcher *cgid_wb_tbd
    = new cgi_dispatcher("tbd",&websearch_api_compat::cgi_tbd_compat, NULL, TRUE);
    _cgi_dispatchers.push_back(cgid_wb_tbd);
  }

  websearch_api_compat::~websearch_api_compat()
  {
  }

  sp_err websearch_api_compat::cgi_search_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");

        // check for action.
        const char *action = miscutil::lookup(parameters,"action");
        if (!action || strcasecmp(action,"expand")==0
            || strcasecmp(action,"page")==0)
          {
            // route to /search/txt
            free(csp->_http._path);
            std::string path = "/search/txt/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_search(csp,rsp,parameters);
          }
        else if (strcasecmp(action,"types")==0)
          {
            // route to /cluster/types
            free(csp->_http._path);
            std::string path = "/cluster/types/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_clustered_types(csp,rsp,parameters);
          }
        else if (strcasecmp(action,"clusterize")==0)
          {
            // route to /cluster/auto
            free(csp->_http._path);
            std::string path = "/cluster/auto/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_clusterize(csp,rsp,parameters);
          }
        else if (strcasecmp(action,"similarity")==0)
          {
            // route to /similar/txt
            free(csp->_http._path);
            std::string path = "/similar/txt/" + query;
            csp->_http._path = strdup(path.c_str());
            return websearch::cgi_websearch_similarity(csp,rsp,parameters);
          }
        else return SP_ERR_CGI_PARAMS;
      }
    else return SP_ERR_CGI_PARAMS;
  }

  sp_err websearch_api_compat::cgi_search_cache_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");

        // check for url.
        const char *url_str = miscutil::lookup(parameters,"url");
        if (!url_str)
          return SP_ERR_CGI_PARAMS;
        std::string url = url_str;
        std::transform(url.begin(),url.end(),url.begin(),tolower);
        std::string surl = urlmatch::strip_url(url);
        uint32_t id = mrf::mrf_single_feature(surl);
        std::string sid = miscutil::to_string(id);
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");

        // route to /cache
        free(csp->_http._path);
        std::string path = "/cache/txt/" + query + "/" + sid;
        csp->_http._path = strdup(path.c_str());
        return websearch::cgi_websearch_search_cache(csp,rsp,parameters);
      }
    else return SP_ERR_CGI_PARAMS;
  }

  sp_err websearch_api_compat::cgi_qc_redir_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");

        // redirection.
        miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>\
                                (parameters),"redirect",1,"1",1);

        // check for url.
        const char *url_str = miscutil::lookup(parameters,"url");
        if (!url_str)
          return SP_ERR_CGI_PARAMS;
        std::string url = url_str;
        std::transform(url.begin(),url.end(),url.begin(),tolower);
        std::string surl = urlmatch::strip_url(url);
        uint32_t id = mrf::mrf_single_feature(surl);
        std::string sid = miscutil::to_string(id);
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");

        // route to POST /search/txt
        free(csp->_http._path);
        std::string path = "/search/txt/" + query + "/" + sid;
        csp->_http._path = strdup(path.c_str());
        free(csp->_http._gpc);
        csp->_http._gpc = strdup("post");
        return websearch::cgi_websearch_search(csp,rsp,parameters);
      }
    else return SP_ERR_CGI_PARAMS;
  }

  sp_err websearch_api_compat::cgi_tbd_compat(client_state *csp,
      http_response *rsp,
      const hash_map<const char*,const char*,hash<const char*>,eqstr> *parameters)
  {
    if (!parameters->empty())
      {
        // check for query.
        const char *query_str = miscutil::lookup(parameters,"q");
        if (!query_str || strlen(query_str) == 0)
          return SP_ERR_CGI_PARAMS;
        std::string query = query_str;
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"q");

        // check for url.
        const char *url_str = miscutil::lookup(parameters,"url");
        if (!url_str)
          return SP_ERR_CGI_PARAMS;
        std::string url = url_str;
        std::transform(url.begin(),url.end(),url.begin(),tolower);
        std::string surl = urlmatch::strip_url(url);
        uint32_t id = mrf::mrf_single_feature(surl);
        std::string sid = miscutil::to_string(id);
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");

        // route to DELETE /search/txt
        free(csp->_http._path);
        std::string path = "/search/txt/" + query + "/" + sid;
        csp->_http._path = strdup(path.c_str());
        free(csp->_http._gpc);
        csp->_http._gpc = strdup("delete");
        sp_err err = websearch::cgi_websearch_search(csp,rsp,parameters);
        if (err != SP_ERR_OK)
          return err;
        miscutil::unmap(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"url");
        miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"action",1,"expand",1);
        miscutil::add_map_entry(const_cast<hash_map<const char*,const char*,hash<const char*>,eqstr>*>(parameters),"output",1,"html",1);

        //return websearch_api_compat::cgi_search_compat(csp,rsp,parameters);
        free(csp->_http._gpc);
        csp->_http._gpc = strdup("get");
        free(csp->_http._path);
        path = "/search/txt/" + query;
        csp->_http._path = strdup(path.c_str());
        return websearch::cgi_websearch_search(csp,rsp,parameters);
      }
    else return SP_ERR_CGI_PARAMS;
  }

  /* plugin registration */
  extern "C"
  {
    plugin* maker()
    {
      return new websearch_api_compat;
    }
  }

} /* end of namespace. */
<|endoftext|>


<commit_before>#include "Bullet.h"

#include <math.h>

using namespace tdr;

void tdr::Bullet::update() {
	if (useRadial) {
		int32_t nxs, nxy;
		sincos(angle, nxs, nxy);
		xs = multiply1616By230(speed, nxs);
		ys = multiply1616By230(speed, nxs);
	} else {
		rectp(xs, ys, speed, angle);
	}
	hitbox.c.x += xs;
	hitbox.c.y += ys;
	xs += xa;
	ys += ya;
	if (delay != 0) --delay;
	if (!detachVisualAndMovementAngles) visualAngle = angle;
	refreshGraze();
}

bool tdr::Bullet::graze() {
	if (timeToNextGraze != 0 || grazeFrequency == -1) return false;
	timeToNextGraze = grazeFrequency == 0 ? -1 : grazeFrequency - 1;
	return true;
}

void tdr::Bullet::refreshGraze() {
	if (timeToNextGraze != 0 && grazeFrequency != -1) --timeToNextGraze;
}

const char* tdr::BL_VERTEX_SOURCE = "\
#version 330 core \n\
layout (location = 0) in vec2 bounds; \n\
layout (location = 1) in vec2 position; \n\
layout (location = 2) in vec3 awl; \n\
layout (location = 3) in vec4 shottc; \n\
out vec2 texCoord; \n\
uniform vec2 texDimensions; \n\
uniform vec2 screenDimensions; \n\
\n\
void main() { \n\
	texCoord = vec2(mix(shottc.x, shottc.z, bounds.x), mix(shottc.y, shottc.w, bounds.y)) / texDimensions; \n\
	float angle = awl.x * 2 * 3.14159265358979323; \n\
	mat2 rm = mat2(cos(angle), -sin(angle), sin(angle), cos(angle)); \n\
	vec2 pos = position / screenDimensions + rm * ((bounds * vec2(2.0f, 2.0f) - vec2(1.0f, 1.0f)) * awl.zy); \n\
	gl_Position = vec4(position * vec2(2.0f, -2.0f) + vec2(-1.0f, 1.0f), 1.0f, 1.0f); \n\
} \
";
const char* tdr::BL_FRAGMENT_SOURCE = "\
#version 330 core \n\
in vec2 texCoord; \n\
out vec4 color; \n\
uniform sampler2D tex; \n\
\n\
void main() { \n\
	color = texture(tex, texCoord); \n\
} \
";

void tdr::BulletList::setUp() {
	if (p == nullptr)
		throw "What, are you crazy?!";
	agl::Shader vertex(BL_VERTEX_SOURCE, GL_VERTEX_SHADER);
	agl::Shader fragment(BL_FRAGMENT_SOURCE, GL_FRAGMENT_SHADER);
	program.attach(vertex);
	program.attach(fragment);
	program.link();
	hasInitializedProgram = true;
	vao.setActive();
	// Vertex data
	vbo.feedData(sizeof(agl::rectangleVertices), (void*) agl::rectangleVertices, GL_DYNAMIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*) 0);
	// InstanceData
	instanceVBO.setActive();
	instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
	// The shader needs to know about the following fields:
	// hitbox.c.x hitbox.c.y
	// visualAngle visualWidth visualLength
	// texcoords
	// So, without further ado:
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FIXED, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, hitbox.c.x));
	glVertexAttribDivisor(1, 1);
	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 3, GL_UNSIGNED_INT, true, sizeof(Bullet), (GLvoid*) offsetof(Bullet, visualAngle));
	glVertexAttribDivisor(2, 1);
	glEnableVertexAttribArray(3);
	glVertexAttribPointer(3, 4, GL_SHORT, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, texcoords));
	glVertexAttribDivisor(3, 1);
	agl::resetVBO();
	agl::resetVAO();
}

void tdr::BulletList::setUniforms() {
	if (hasSetUniforms) return;
	vao.setActive();
	program.use();
	shotsheet.bindTo(0);
	SETUNSP(program, 1i, "tex", 0);
	SETUNSP2(program, 2f, "texDimensions", (GLfloat) shotsheet.getWidth(), (GLfloat) shotsheet.getHeight());
	SETUNSP2(program, 2f, "screenDimensions", (GLfloat) p->width(), (GLfloat) p->height());
	hasSetUniforms = true;
}

void tdr::BulletList::tick() {
	p->getFBO().setActive();
	glEnable(GL_BLEND);
	agl::BM_ALPHA.use();
	glDisable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);
	setUniforms();
	glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, bullets.size());
	agl::resetVAO();
}

void tdr::BulletList::update() {
	instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
}

void tdr::BulletList::_tearDown() {
}

bool tdr::BulletList::check(const Circle& h) {
	for (Bullet& b : bullets) {
		if (!b.collides) continue;
		if (b.isLaser ?
				doCirclesIntersect(b.hitbox.c, h) :
				doCircleAndLineIntersect(h, b.hitbox.l))
			return true;
	}
	return false;
}

bool tdr::BulletList::check(const Line& h) {
	for (Bullet& b : bullets) {
		if (!b.collides) continue;
		if (b.isLaser ?
				doCircleAndLineIntersect(b.hitbox.c, h) :
				doLinesIntersect(h, b.hitbox.l))
			return true;
	}
	return false;
}

void tdr::BulletList::updatePositions(const agl::IRect16& bounds) {
	for (Bullet& b : bullets) {
		b.update();
		if (b.deleteWhenOutOfBounds && (
				b.hitbox.c.x < bounds.left ||
				b.hitbox.c.x > bounds.right ||
				b.hitbox.c.y < bounds.top ||
				b.hitbox.c.y > bounds.bottom))
			b.markedForDeletion = 1;
	}
	// Remove marked bullets from list
	unsigned int ahead = 0;
	unsigned int behind = 0;
	for (ahead = 0; ahead < bullets.size(); ++ahead) {
		if (!bullets[ahead].markedForDeletion) {
			if (ahead != behind) bullets[behind] = bullets[ahead];
			++behind;
		}
	}
	bullets.resize(behind);
}

void tdr::BulletList::insert(Bullet& b) {
	b.id = highestID++;
	bullets.push_back(b);
}

Bullet* tdr::BulletList::query(uint64_t id) {
	unsigned int lower = 0, upper = bullets.size();
	while (upper > lower + 1) { // v this avoids overflow
		unsigned int middle = lower + ((upper - lower) >> 1);
		uint64_t mid = bullets[middle].id;
		if (mid == id) return bullets.data() + middle;
		if (id < mid) upper = middle;
		else lower = middle;
	}
	return bullets[lower].id == id ? bullets.data() + lower : nullptr;
}

void tdr::BulletList::graze(const Circle& h) {
	for (Bullet& b : bullets) {
		if (!b.collides) continue;
		if (b.isLaser ?
				doCirclesIntersect(b.hitbox.c, h) :
				doCircleAndLineIntersect(h, b.hitbox.l))
			b.graze();
	}
}
<commit_msg>Correct shader code<commit_after>#include "Bullet.h"

#include <math.h>

using namespace tdr;

void tdr::Bullet::update() {
	if (useRadial) {
		int32_t nxs, nxy;
		sincos(angle, nxs, nxy);
		xs = multiply1616By230(speed, nxs);
		ys = multiply1616By230(speed, nxs);
	} else {
		rectp(xs, ys, speed, angle);
	}
	hitbox.c.x += xs;
	hitbox.c.y += ys;
	xs += xa;
	ys += ya;
	if (delay != 0) --delay;
	if (!detachVisualAndMovementAngles) visualAngle = angle;
	refreshGraze();
}

bool tdr::Bullet::graze() {
	if (timeToNextGraze != 0 || grazeFrequency == -1) return false;
	timeToNextGraze = grazeFrequency == 0 ? -1 : grazeFrequency - 1;
	return true;
}

void tdr::Bullet::refreshGraze() {
	if (timeToNextGraze != 0 && grazeFrequency != -1) --timeToNextGraze;
}

const char* tdr::BL_VERTEX_SOURCE = "\
#version 330 core \n\
layout (location = 0) in vec2 bounds; \n\
layout (location = 1) in vec2 position; \n\
layout (location = 2) in vec3 awl; \n\
layout (location = 3) in vec4 shottc; \n\
out vec2 texCoord; \n\
uniform vec2 texDimensions; \n\
uniform vec2 screenDimensions; \n\
\n\
void main() { \n\
	texCoord = vec2(mix(shottc.x, shottc.z, bounds.x), mix(shottc.y, shottc.w, bounds.y)) / texDimensions; \n\
	float angle = awl.x * 2 * 3.14159265358979323 / 16384; \n\
	mat2 rm = mat2(cos(angle), -sin(angle), sin(angle), cos(angle)); \n\
	vec2 pos = position / screenDimensions + rm * ((bounds * vec2(2.0f, 2.0f) - vec2(1.0f, 1.0f)) * awl.zy); \n\
	gl_Position = vec4(position * vec2(2.0f, -2.0f) + vec2(-1.0f, 1.0f), 1.0f, 1.0f); \n\
} \
";
const char* tdr::BL_FRAGMENT_SOURCE = "\
#version 330 core \n\
in vec2 texCoord; \n\
out vec4 color; \n\
uniform sampler2D tex; \n\
\n\
void main() { \n\
	color = texture(tex, texCoord); \n\
} \
";

void tdr::BulletList::setUp() {
	if (p == nullptr)
		throw "What, are you crazy?!";
	agl::Shader vertex(BL_VERTEX_SOURCE, GL_VERTEX_SHADER);
	agl::Shader fragment(BL_FRAGMENT_SOURCE, GL_FRAGMENT_SHADER);
	program.attach(vertex);
	program.attach(fragment);
	program.link();
	hasInitializedProgram = true;
	vao.setActive();
	// Vertex data
	vbo.feedData(sizeof(agl::rectangleVertices), (void*) agl::rectangleVertices, GL_DYNAMIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*) 0);
	// InstanceData
	instanceVBO.setActive();
	instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
	// The shader needs to know about the following fields:
	// hitbox.c.x hitbox.c.y
	// visualAngle visualWidth visualLength
	// texcoords
	// So, without further ado:
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FIXED, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, hitbox.c.x));
	glVertexAttribDivisor(1, 1);
	glEnableVertexAttribArray(2);
	glVertexAttribPointer(2, 3, GL_FIXED, true, sizeof(Bullet), (GLvoid*) offsetof(Bullet, visualAngle));
	glVertexAttribDivisor(2, 1);
	glEnableVertexAttribArray(3);
	glVertexAttribPointer(3, 4, GL_SHORT, false, sizeof(Bullet), (GLvoid*) offsetof(Bullet, texcoords));
	glVertexAttribDivisor(3, 1);
	agl::resetVBO();
	agl::resetVAO();
}

void tdr::BulletList::setUniforms() {
	if (hasSetUniforms) return;
	vao.setActive();
	program.use();
	shotsheet.bindTo(0);
	SETUNSP(program, 1i, "tex", 0);
	SETUNSP2(program, 2f, "texDimensions", (GLfloat) shotsheet.getWidth(), (GLfloat) shotsheet.getHeight());
	SETUNSP2(program, 2f, "screenDimensions", (GLfloat) p->width(), (GLfloat) p->height());
	hasSetUniforms = true;
}

void tdr::BulletList::tick() {
	p->getFBO().setActive();
	glEnable(GL_BLEND);
	agl::BM_ALPHA.use();
	glDisable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);
	setUniforms();
	glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, bullets.size());
	agl::resetVAO();
}

void tdr::BulletList::update() {
	instanceVBO.feedData(bullets.size() * sizeof(Bullet), bullets.data(), GL_DYNAMIC_DRAW);
}

void tdr::BulletList::_tearDown() {
}

bool tdr::BulletList::check(const Circle& h) {
	for (Bullet& b : bullets) {
		if (!b.collides) continue;
		if (b.isLaser ?
				doCirclesIntersect(b.hitbox.c, h) :
				doCircleAndLineIntersect(h, b.hitbox.l))
			return true;
	}
	return false;
}

bool tdr::BulletList::check(const Line& h) {
	for (Bullet& b : bullets) {
		if (!b.collides) continue;
		if (b.isLaser ?
				doCircleAndLineIntersect(b.hitbox.c, h) :
				doLinesIntersect(h, b.hitbox.l))
			return true;
	}
	return false;
}

void tdr::BulletList::updatePositions(const agl::IRect16& bounds) {
	for (Bullet& b : bullets) {
		b.update();
		if (b.deleteWhenOutOfBounds && (
				b.hitbox.c.x < bounds.left ||
				b.hitbox.c.x > bounds.right ||
				b.hitbox.c.y < bounds.top ||
				b.hitbox.c.y > bounds.bottom))
			b.markedForDeletion = 1;
	}
	// Remove marked bullets from list
	unsigned int ahead = 0;
	unsigned int behind = 0;
	for (ahead = 0; ahead < bullets.size(); ++ahead) {
		if (!bullets[ahead].markedForDeletion) {
			if (ahead != behind) bullets[behind] = bullets[ahead];
			++behind;
		}
	}
	bullets.resize(behind);
}

void tdr::BulletList::insert(Bullet& b) {
	b.id = highestID++;
	bullets.push_back(b);
}

Bullet* tdr::BulletList::query(uint64_t id) {
	unsigned int lower = 0, upper = bullets.size();
	while (upper > lower + 1) { // v this avoids overflow
		unsigned int middle = lower + ((upper - lower) >> 1);
		uint64_t mid = bullets[middle].id;
		if (mid == id) return bullets.data() + middle;
		if (id < mid) upper = middle;
		else lower = middle;
	}
	return bullets[lower].id == id ? bullets.data() + lower : nullptr;
}

void tdr::BulletList::graze(const Circle& h) {
	for (Bullet& b : bullets) {
		if (!b.collides) continue;
		if (b.isLaser ?
				doCirclesIntersect(b.hitbox.c, h) :
				doCircleAndLineIntersect(h, b.hitbox.l))
			b.graze();
	}
}
<|endoftext|>


<commit_before><commit_msg>coverity#984422 unused pointer value<commit_after><|endoftext|>


<commit_before><commit_msg>Remove commented out code<commit_after><|endoftext|>


<commit_before><commit_msg>SwPagePreView: fix some scrollbar bugs (still not perfect, just a quick fix)<commit_after><|endoftext|>