// Check accuracy of style transfer models from https://github.com/jcjohnson/fast-neural-style
// th fast_neural_style.lua \
//   -input_image ~/opencv_extra/testdata/dnn/googlenet_1.png \
//   -output_image lena.png \
//   -median_filter 0 \
//   -image_size 0 \
//   -model models/eccv16/starry_night.t7
// th fast_neural_style.lua \
//   -input_image ~/opencv_extra/testdata/dnn/googlenet_1.png \
//   -output_image lena.png \
//   -median_filter 0 \
//   -image_size 0 \
//   -model models/instance_norm/feathers.t7
TEST_P(Test_Torch_nets, FastNeuralStyle_accuracy)
{
    std::string models[] = {"dnn/fast_neural_style_eccv16_starry_night.t7",
                            "dnn/fast_neural_style_instance_norm_feathers.t7"};
    std::string targets[] = {"dnn/lena_starry_night.png", "dnn/lena_feathers.png"};

    for (int i = 0; i < 2; ++i)
    {
        const string model = findDataFile(models[i], false);
        Net net = readNetFromTorch(model);

        net.setPreferableTarget(GetParam());

        Mat img = imread(findDataFile("dnn/googlenet_1.png", false));
        Mat inputBlob = blobFromImage(img, 1.0, Size(), Scalar(103.939, 116.779, 123.68), false);

        net.setInput(inputBlob);
        Mat out = net.forward();

        // Deprocessing.
        getPlane(out, 0, 0) += 103.939;
        getPlane(out, 0, 1) += 116.779;
        getPlane(out, 0, 2) += 123.68;
        out = cv::min(cv::max(0, out), 255);

        Mat ref = imread(findDataFile(targets[i]));
        Mat refBlob = blobFromImage(ref, 1.0, Size(), Scalar(), false);

        normAssert(out, refBlob, "", 0.5, 1.1);
    }
}
示例#2
0
    void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
    {
        CV_Assert(blobs.size() == 1 + hasBias);

        for (size_t ii = 0; ii < outputs.size(); ii++)
        {
            Mat &inpBlob = *inputs[ii];
            Mat &outBlob = outputs[ii];

            CV_Assert(inpBlob.size[1] == blobs[0].total());
            if (hasBias)
                CV_Assert(inpBlob.size[1] == blobs[1].total());

            CV_Assert(inpBlob.type() == CV_32F && outBlob.type() == CV_32F);

            for( int cn = 0; cn < inpBlob.size[0]; cn++ )
            {
                for (int n = 0; n < inpBlob.size[1]; n++)
                {
                    float w = blobs[0].at<float>(n);
                    float b = hasBias ? blobs[1].at<float>(n) : 0;
                    Mat outBlobPlane = getPlane(outBlob, cn, n);
                    Mat inpBlobPlane = getPlane(inpBlob, cn, n);
                    inpBlobPlane.convertTo(outBlobPlane, CV_32F, w, b);
                }
            }
        }
    }
示例#3
0
bool arlCore::Tag::setRegistration( unsigned int plane, arlCore::vnl_rigid_matrix &T, long int date, long int time, bool reset )
{
    //VAG FIXME setTime(date,time);
    //std::vector<double> errors;
    //T.RMS3D3D( m_geometry, m_measures, errors);
    const double Error = T.getRMS();
    if(m_registrationMaxError>=0 && Error>m_registrationMaxError)
    {
        m_measuresPlane = arlCore::PlaneSystem::NoPlane;
        getPlaneSystem().resetTrf( getPlane(), plane );
        //VAG FIXME  m_log<<"REGISTRATION FAILED : RMS="<<Error<<" > RMSMax="<<m_registrationMaxError<<"\n";
        //VAG FIXME  log(ARLCORE_LOG_WARNING);
        return false;
    }
    if(reset) this->reset();
    unsigned int i;
    for( i=0 ; i<m_geometry->size() ; ++i )
    {
        if(i>=m_measures->size())
        {
            m_measures->push_back( (*m_geometry)[i]);
            (*m_measures)[i]->setVisible(false);
        }
        if(!(*m_measures)[i]->isVisible())
        {
            assert(m_measures->size()>=i);
            T.trf( (*m_geometry)[i],(*m_measures)[i]);
            (*m_measures)[i]->setVisible(true);
        }
    }
    bool b = getPlaneSystem().setTrf( getPlane(), plane, T, date,time );
    if(b) m_measuresPlane=plane;
    return b;
}
DisplayPlane* TngPlaneManager::getPlaneHelper(int dsp, int type)
{
    RETURN_NULL_IF_NOT_INIT();

    if (dsp < 0 || dsp > IDisplayDevice::DEVICE_EXTERNAL) {
        ETRACE("Invalid display device %d", dsp);
        return 0;
    }

    int index = dsp == IDisplayDevice::DEVICE_PRIMARY ? 0 : 1;

    if (type == DisplayPlane::PLANE_PRIMARY ||
        type == DisplayPlane::PLANE_CURSOR) {
        return getPlane(type, index);
    } else if (type == DisplayPlane::PLANE_SPRITE) {
        return getAnyPlane(type);
    } else if (type == DisplayPlane::PLANE_OVERLAY) {
        // use overlay A for pipe A and overlay C for pipe B if possible
        DisplayPlane *plane = getPlane(type, index);
        if (plane == NULL) {
            plane = getPlane(type, !index);
        }
        return plane;
    } else {
        ETRACE("invalid plane type %d", type);
        return 0;
    }
}
示例#5
0
// Check accuracy of style transfer models from https://github.com/jcjohnson/fast-neural-style
// th fast_neural_style.lua \
//   -input_image ~/opencv_extra/testdata/dnn/googlenet_1.png \
//   -output_image lena.png \
//   -median_filter 0 \
//   -image_size 0 \
//   -model models/eccv16/starry_night.t7
// th fast_neural_style.lua \
//   -input_image ~/opencv_extra/testdata/dnn/googlenet_1.png \
//   -output_image lena.png \
//   -median_filter 0 \
//   -image_size 0 \
//   -model models/instance_norm/feathers.t7
TEST_P(Test_Torch_nets, FastNeuralStyle_accuracy)
{
    checkBackend();

#if defined(INF_ENGINE_RELEASE)
#if INF_ENGINE_RELEASE <= 2018050000
    if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_OPENCL)
        throw SkipTestException("");
#endif
#endif

    std::string models[] = {"dnn/fast_neural_style_eccv16_starry_night.t7",
                            "dnn/fast_neural_style_instance_norm_feathers.t7"};
    std::string targets[] = {"dnn/lena_starry_night.png", "dnn/lena_feathers.png"};

    for (int i = 0; i < 2; ++i)
    {
        const string model = findDataFile(models[i], false);
        Net net = readNetFromTorch(model);

        net.setPreferableBackend(backend);
        net.setPreferableTarget(target);

        Mat img = imread(findDataFile("dnn/googlenet_1.png", false));
        Mat inputBlob = blobFromImage(img, 1.0, Size(), Scalar(103.939, 116.779, 123.68), false);

        net.setInput(inputBlob);
        Mat out = net.forward();

        // Deprocessing.
        getPlane(out, 0, 0) += 103.939;
        getPlane(out, 0, 1) += 116.779;
        getPlane(out, 0, 2) += 123.68;
        out = cv::min(cv::max(0, out), 255);

        Mat ref = imread(findDataFile(targets[i]));
        Mat refBlob = blobFromImage(ref, 1.0, Size(), Scalar(), false);

        if (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD)
        {
            double normL1 = cvtest::norm(refBlob, out, cv::NORM_L1) / refBlob.total();
            if (target == DNN_TARGET_MYRIAD)
                EXPECT_LE(normL1, 4.0f);
            else
                EXPECT_LE(normL1, 0.6f);
        }
        else
            normAssert(out, refBlob, "", 0.5, 1.1);
    }
}
示例#6
0
bool SDLVideo::processOneFrame(Data data) {
	SDL_Event event;
	while (SDL_PollEvent(&event)) {
		switch (event.type) {
		case SDL_WINDOWEVENT:
			if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
				SDL_RenderSetViewport(renderer, nullptr);
				displayrect->w = event.window.data1;
				displayrect->h = event.window.data2;
			}
			break;
		case SDL_QUIT:
#ifdef _MSC_VER
			GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
#else
			std::raise(SIGTERM);
#endif
			return false;
		}
	}

	auto pic = safe_cast<const DataPicture>(data);
	if (pic->getFormat() != pictureFormat) {
		pictureFormat = pic->getFormat();
		createTexture();
	}

	auto const now = m_clock->now();
	auto const timestamp = pic->getTime() + PREROLL_DELAY; // assume timestamps start at zero
	auto const delay = std::max<int64_t>(0, timestamp - now);
	auto const delayInMs = clockToTimescale(delay, 1000);
	SDL_Delay((Uint32)delayInMs);

	if (pictureFormat.format == YUV420P) {
		SDL_UpdateYUVTexture(texture, nullptr,
		                     pic->getPlane(0), (int)pic->getPitch(0),
		                     pic->getPlane(1), (int)pic->getPitch(1),
		                     pic->getPlane(2), (int)pic->getPitch(2));
	} else {
		SDL_UpdateTexture(texture, nullptr, pic->getPlane(0), (int)pic->getPitch(0));
	}
	SDL_RenderCopy(renderer, texture, nullptr, displayrect.get());
	SDL_RenderPresent(renderer);

	m_NumFrames++;

	return true;
}
示例#7
0
      void
      MinimalTIFFWriter::setupIFD() const
      {
        // Default to single strips for now.
        ifd->setImageWidth(getSizeX());
        ifd->setImageHeight(getSizeY());

        ifd->setTileType(tiff::STRIP);
        ifd->setTileWidth(getSizeX());
        ifd->setTileHeight(1U);

        ome::compat::array<dimension_size_type, 3> coords = getZCTCoords(getPlane());

        dimension_size_type channel = coords[1];

        ifd->setPixelType(getPixelType());
        ifd->setBitsPerSample(bitsPerPixel(getPixelType()));
        ifd->setSamplesPerPixel(getRGBChannelCount(channel));

        const boost::optional<bool> interleaved(getInterleaved());
        if (isRGB(channel) && interleaved && *interleaved)
          ifd->setPlanarConfiguration(tiff::CONTIG);
        else
          ifd->setPlanarConfiguration(tiff::SEPARATE);

        // This isn't necessarily always true; we might want to use a
        // photometric interpretation other than RGB with three
        // subchannels.
        if (isRGB(channel) && getRGBChannelCount(channel) == 3)
          ifd->setPhotometricInterpretation(tiff::RGB);
        else
          ifd->setPhotometricInterpretation(tiff::MIN_IS_BLACK);
      }
示例#8
0
/**
 * Inverts this face.
 */
void BOP_Face::invert()
{
	getPlane().Invert();
	BOP_Index aux = m_indexs[0];
	m_indexs[0] = m_indexs[2];
	m_indexs[2] = aux;
}
示例#9
0
文件: AABox.cpp 项目: Issacchaos/hifi
bool AABox::findCapsulePenetration(const glm::vec3& start, const glm::vec3& end, float radius, glm::vec3& penetration) const {
    glm::vec4 start4 = glm::vec4(start, 1.0f);
    glm::vec4 end4 = glm::vec4(end, 1.0f);
    glm::vec4 startToEnd = glm::vec4(end - start, 0.0f);
    
    float minPenetrationLength = FLT_MAX;
    for (int i = 0; i < FACE_COUNT; i++) {
        // find the vector from the segment to the closest point on the face (starting from deeper end)
        glm::vec4 facePlane = getPlane((BoxFace)i);
        glm::vec3 closest = (glm::dot(start4, facePlane) <= glm::dot(end4, facePlane)) ?
            getClosestPointOnFace(start4, startToEnd, (BoxFace)i) : getClosestPointOnFace(end4, -startToEnd, (BoxFace)i);
        glm::vec3 vector = -computeVectorFromPointToSegment(closest, start, end);
        if (glm::dot(vector, glm::vec3(facePlane)) < 0.0f) {
            // outside this face, so use vector to closest point to determine penetration
            return ::findSpherePenetration(vector, glm::vec3(-facePlane), radius, penetration);
        }
        float vectorLength = glm::length(vector);
        if (vectorLength < minPenetrationLength) {
            // remember the smallest penetration vector; if we're inside all faces, we'll use that
            penetration = (vectorLength < EPSILON) ? glm::vec3(-facePlane) * radius :
                vector * ((vectorLength + radius) / -vectorLength);
            minPenetrationLength = vectorLength;
        }
    } 
    
    return true;
}
    void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
    {
        CV_Assert(inputs.size() == 2);
        Mat& input = *inputs[0];
        Mat& indices = *inputs[1];

        CV_Assert(input.total() == indices.total());
        CV_Assert(input.size[0] == 1);
        CV_Assert(input.isContinuous());

        for(int i_n = 0; i_n < outputs.size(); i_n++)
        {
            Mat& outBlob = outputs[i_n];
            outBlob.setTo(0);
            CV_Assert(input.size[1] == outBlob.size[1]);
            int outPlaneTotal = outBlob.size[2]*outBlob.size[3];

            for (int i_c = 0; i_c < input.size[1]; i_c++)
            {
                Mat outPlane = getPlane(outBlob, 0, i_c);
                int wh_area = input.size[2]*input.size[3];
                const float* inptr = input.ptr<float>(0, i_c);
                const float* idxptr = indices.ptr<float>(0, i_c);
                float* outptr = outPlane.ptr<float>();

                for(int i_wh = 0; i_wh < wh_area; i_wh++)
                {
                    int index = idxptr[i_wh];
                    CV_Assert(0 <= index && index < outPlaneTotal);
                    outptr[index] = inptr[i_wh];
                }
            }
        }
    }
//------------------------------------------------------------------------------
void ShadowVolumeBSP::clipPoly(SVNode * root, SVPoly ** store, SVPoly * poly)
{
    if(!root)
    {
        recyclePoly(poly);
        return;
    }

    const PlaneF & plane = getPlane(root->mPlaneIndex);

    switch(whichSide(poly, plane))
    {
    case SVNode::On:
    case SVNode::Back:
        if(root->mBack)
            clipPoly(root->mBack, store, poly);
        else
            addToPolyList(store, poly);
        break;

    case SVNode::Front:
        // encountered POLY node?
        if(!root->mFront)
        {
            recyclePoly(poly);
            return;
        }
        else
            clipPoly(root->mFront, store, poly);
        break;

    case SVNode::Split:
    {
        SVPoly * front;
        SVPoly * back;

        splitPoly(poly, plane, &front, &back);
        AssertFatal(front && back, "ShadowVolumeBSP::clipPoly: invalid split");
        recyclePoly(poly);

        // front
        if(!root->mFront)
        {
            recyclePoly(front);
            return;
        }
        else
            clipPoly(root->mFront, store, front);

        // back
        if(root->mBack)
            clipPoly(root->mBack, store, back);
        else
            addToPolyList(store, back);
        break;
    }
    }
}
示例#12
0
    void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
    {
        CV_TRACE_FUNCTION();
        CV_TRACE_ARG_VALUE(name, "name", name.c_str());

        if (paddingType == "constant")
        {
            outputs[0].setTo(paddingValue);
            inputs[0]->copyTo(outputs[0](dstRanges));
        }
        else if (paddingType == "reflect")
        {
            CV_Assert(inputs.size() == 1);
            CV_Assert(outputs.size() == 1);
            CV_Assert(inputs[0]->dims == 4);
            CV_Assert(outputs[0].dims == 4);

            if (inputs[0]->size[0] != outputs[0].size[0] || inputs[0]->size[1] != outputs[0].size[1])
                CV_Error(Error::StsNotImplemented, "Only spatial reflection padding is supported.");

            const int inpHeight = inputs[0]->size[2];
            const int inpWidth = inputs[0]->size[3];
            const int outHeight = outputs[0].size[2];
            const int outWidth = outputs[0].size[3];
            const int padTop = dstRanges[2].start;
            const int padBottom = outHeight - dstRanges[2].end;
            const int padLeft = dstRanges[3].start;
            const int padRight = outWidth - dstRanges[3].end;
            CV_Assert(padTop < inpHeight, padBottom < inpHeight,
                      padLeft < inpWidth, padRight < inpWidth);

            for (size_t n = 0; n < inputs[0]->size[0]; ++n)
            {
                for (size_t ch = 0; ch < inputs[0]->size[1]; ++ch)
                {
                    copyMakeBorder(getPlane(*inputs[0], n, ch),
                                   getPlane(outputs[0], n, ch),
                                   padTop, padBottom, padLeft, padRight,
                                   BORDER_REFLECT_101);
                }
            }
        }
        else
            CV_Error(Error::StsNotImplemented, "Unknown padding type: " + paddingType);
    }
DisplayPlane* DisplayPlaneManager::getAnyPlane(int type)
{
    RETURN_NULL_IF_NOT_INIT();

    if (type < 0 || type >= DisplayPlane::PLANE_MAX) {
        ETRACE("Invalid plane type %d", type);
        return 0;
    }

    int freePlaneIndex = getPlane(mReclaimedPlanes[type]);
    if (freePlaneIndex >= 0)
        return mPlanes[type].itemAt(freePlaneIndex);

    freePlaneIndex = getPlane(mFreePlanes[type]);
    if (freePlaneIndex >= 0)
        return mPlanes[type].itemAt(freePlaneIndex);

    return 0;
}
    void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals)
    {
        CV_TRACE_FUNCTION();
        CV_TRACE_ARG_VALUE(name, "name", name.c_str());

        if (outHeight == inputs[0]->size[2] && outWidth == inputs[0]->size[3])
            return;

        Mat& inp = *inputs[0];
        Mat& out = outputs[0];
        for (size_t n = 0; n < inputs[0]->size[0]; ++n)
        {
            for (size_t ch = 0; ch < inputs[0]->size[1]; ++ch)
            {
                resize(getPlane(inp, n, ch), getPlane(out, n, ch),
                       Size(outWidth, outHeight), 0, 0, INTER_NEAREST);
            }
        }
    }
示例#15
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void WriteImages::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
  reader->openFilterGroup(this, index);
  setImagePrefix( reader->readString("ImagePrefix", getImagePrefix()) );
  setFilePrefix( reader->readValue("FilePrefix", getFilePrefix()) );
  setOutputPath( reader->readString("OutputPath", getOutputPath()) );
  setColorsArrayPath( reader->readDataArrayPath("ColorsArrayPath", getColorsArrayPath()) );
  setImageFormat( reader->readValue("ImageFormat", getImageFormat()) );
  setPlane(reader->readValue("Plane", getPlane()));
  reader->closeFilterGroup();
}
示例#16
0
      void
      MinimalTIFFWriter::setPlane(dimension_size_type plane) const
      {
        const dimension_size_type currentPlane = getPlane();
        detail::FormatWriter::setPlane(plane);

        if (currentPlane != plane)
          {
            nextIFD();
            setupIFD();
          }
      }
示例#17
0
文件: AABox.cpp 项目: Issacchaos/hifi
bool AABox::findSpherePenetration(const glm::vec3& center, float radius, glm::vec3& penetration) const {
    glm::vec4 center4 = glm::vec4(center, 1.0f);
    
    float minPenetrationLength = FLT_MAX;
    for (int i = 0; i < FACE_COUNT; i++) {
        glm::vec4 facePlane = getPlane((BoxFace)i);
        glm::vec3 vector = getClosestPointOnFace(center, (BoxFace)i) - center;
        if (glm::dot(center4, getPlane((BoxFace)i)) >= 0.0f) {
            // outside this face, so use vector to closest point to determine penetration
            return ::findSpherePenetration(vector, glm::vec3(-facePlane), radius, penetration);
        }
        float vectorLength = glm::length(vector);
        if (vectorLength < minPenetrationLength) {
            // remember the smallest penetration vector; if we're inside all faces, we'll use that
            penetration = (vectorLength < EPSILON) ? glm::vec3(-facePlane) * radius :
                vector * ((vectorLength + radius) / -vectorLength);
            minPenetrationLength = vectorLength;
        }
    }
    
    return true;
}
示例#18
0
    void spatialNormalization(Mat &srcBlob, Mat &dstBlob)
    {
        int num = srcBlob.size[0];
        int channels = srcBlob.size[1];
        int sizeNormFactor = normBySize ? size*size : 1;

        Mat srcMat = srcBlob;
        Mat dstMat = dstBlob;

        for (int n = 0; n < num; n++)
        {
            for (int cn = 0; cn < channels; cn++)
            {
                Mat src = getPlane(srcMat, n, cn);
                Mat dst = getPlane(dstMat, n, cn);

                sqrBoxFilter_(src, dst);

                dst.convertTo(dst, dst.type(), alpha/sizeNormFactor, bias);
                cv::pow(dst, beta, dst);
                cv::divide(src, dst, dst);
            }
        }
    }
//------------------------------------------------------------------------------
bool ShadowVolumeBSP::testPoly(SVNode * root, SVPoly * poly)
{
    const PlaneF & plane = getPlane(root->mPlaneIndex);
    switch(whichSide(poly, plane))
    {
    case SVNode::On:
    case SVNode::Front:
        if(root->mFront)
            return(testPoly(root->mFront, poly));

        recyclePoly(poly);
        return(true);

    case SVNode::Back:
        if(root->mBack)
            return(testPoly(root->mBack, poly));
        recyclePoly(poly);
        break;

    case SVNode::Split:
    {
        if(!root->mFront)
        {
            recyclePoly(poly);
            return(true);
        }

        SVPoly * front;
        SVPoly * back;

        splitPoly(poly, plane, &front, &back);
        recyclePoly(poly);

        if(testPoly(root->mFront, front))
        {
            recyclePoly(back);
            return(true);
        }

        if(root->mBack)
            return(testPoly(root->mBack, back));

        recyclePoly(back);
        break;
    }
    }
    return(false);
}
示例#20
0
BruntonPrimitive::BruntonPrimitive(const LidarOctree* octree,const Primitive::Vector& translation,Cluster::MulticastPipe* pipe)
	:PlanePrimitive(octree,translation,pipe)
	{
	/* Print the strike and dip angles: */
	Vector normal=getPlane().getNormal();
	if(normal[2]<Scalar(0))
		normal=-normal;
	Scalar dipAngle=Math::acos(normal[2]/Geometry::mag(normal));
	normal[2]=Scalar(0);
	Scalar strikeAngle=Math::atan2(normal[0],normal[1]);
	if(strikeAngle<Scalar(0))
		strikeAngle+=Scalar(2)*Math::Constants<Scalar>::pi;
	std::cout<<"Strike angle: "<<Math::deg(strikeAngle)<<std::endl;
	std::cout<<"Dip angle: "<<Math::deg(dipAngle)<<std::endl;
	
	buildBrunton();
	}
示例#21
0
文件: rend.cpp 项目: Baltiless/github
void DoLEE(GzRender* render, GzCoord* tri)
{
	/*
	float x1, y1, z1;
	float x2, y2, z2;
	float x3, y3, z3;
	*/
	GzPixel* pixel;
	vert vert1,vert2,vert3;
	edge triEdge[3];
	checkBound bound;
	plane triPlane;
	//GzCoord *tri = (GzCoord*)verts[0];
	GzDepth orgZ = 0; //depth
    
    //put value into verts
	putVertValue(tri[0], &vert1.coord);
	putVertValue(tri[1], &vert2.coord);
	putVertValue(tri[2], &vert3.coord);
    
    //sort verts using Y value
	getTri(&vert1, &vert2, &vert3, triEdge);
	getPlane(triEdge[0], triEdge[1], &triPlane, vert1);

	//get a rectangle bound to check value
	getCheckBound(&bound, vert1, vert2, vert3);
	//TRACE("minX: %f, maxX:  %f, minY: %f, maxY: %f \n", bound.minX, bound.maxX,bound.minY, bound.maxY);
	for(int i = bound.minY; i <= bound.maxY; i++)
	{
		for(int j = bound.minX; j <=bound.maxX; j++)
		{
			if(checkValid(j, i, triEdge)){             //implement later
				if((orgZ = getFbuf(render, j, i)) == -1)/*render->display->fbuf[RENDARRAY(j,i)].z;*/
				{
					continue;
				}
				//TRACE("orgZ = %d\n", orgZ);
				if(checkZBuffer(j, i, triPlane,&orgZ)){
					GzPutDisplay(render->display, j, i, ctoi(render->flatcolor[0]), ctoi(render->flatcolor[1]), ctoi(render->flatcolor[2]), 1, orgZ);
					//GzPutDisplay
				}
			}
		}
	}

}
void ShadowVolumeBSP::insertPoly(SVNode ** root, SVPoly * poly)
{
    if(!(*root))
    {
        insertShadowVolume(root, poly->mShadowVolume);

        if(poly->mSurfaceInfo && !mFirstInteriorNode)
            mFirstInteriorNode = mShadowVolumes[poly->mShadowVolume];

        if(poly->mTarget)
            addUniqueVolume(poly->mTarget->mSurfaceInfo, poly->mShadowVolume);

        recyclePoly(poly);
        return;
    }

    const PlaneF & plane = getPlane((*root)->mPlaneIndex);

    //
    switch(whichSide(poly, plane))
    {
    case SVNode::On:
    case SVNode::Front:
        insertPolyFront(root, poly);
        break;

    case SVNode::Back:
        insertPolyBack(root, poly);
        break;

    case SVNode::Split:
    {
        SVPoly * front;
        SVPoly * back;

        splitPoly(poly, plane, &front, &back);
        recyclePoly(poly);

        insertPolyFront(root, front);
        insertPolyBack(root, back);

        break;
    }
    }
}
bool ShadowVolumeBSP::testPoint(SVNode * root, const Point3F & pnt)
{
    const PlaneF & plane = getPlane(root->mPlaneIndex);
    switch(plane.whichSide(pnt))
    {
    case PlaneF::On:

        if(!root->mFront)
            return(true);
        else
        {
            if(testPoint(root->mFront, pnt))
                return(true);
            else
            {
                if(!root->mBack)
                    return(false);
                else
                    return(testPoint(root->mBack, pnt));
            }
        }
        break;

    //
    case PlaneF::Front:
        if(root->mFront)
            return(testPoint(root->mFront, pnt));
        else
            return(true);
        break;

    //
    case PlaneF::Back:
        if(root->mBack)
            return(testPoint(root->mBack, pnt));
        else
            return(false);
        break;
    }

    return(false);
}
// clip a poly to it's own shadow volume
void ShadowVolumeBSP::clipToSelf(SVNode * root, SVPoly ** store, SVPoly * poly)
{
    if(!root)
    {
        addToPolyList(store, poly);
        return;
    }

    const PlaneF & plane = getPlane(root->mPlaneIndex);

    switch(whichSide(poly, plane))
    {
    case SVNode::Front:
        clipToSelf(root->mFront, store, poly);
        break;

    case SVNode::On:
        addToPolyList(store, poly);
        break;

    case SVNode::Back:
        recyclePoly(poly);
        break;

    case SVNode::Split:
    {
        SVPoly * front = 0;
        SVPoly * back = 0;
        splitPoly(poly, plane, &front, &back);
        AssertFatal(front && back, "ShadowVolumeBSP::clipToSelf: invalid split");

        recyclePoly(poly);
        recyclePoly(back);

        clipToSelf(root->mFront, store, front);
        break;
    }
    }
}
示例#25
0
      void
      FormatWriter::setPlane(dimension_size_type plane) const
      {
        assertId(currentId, true);

        if (plane >= getImageCount())
          {
            boost::format fmt("Invalid plane: %1%");
            fmt % plane;
            throw std::logic_error(fmt.str());
          }

        const dimension_size_type currentPlane = getPlane();
        if (currentPlane != plane &&
            (plane > 0 && currentPlane != plane - 1))
          {
            boost::format fmt("Plane set out of order: %1% (currently %2%)");
            fmt % plane % currentPlane;
            throw std::logic_error(fmt.str());
          }

        this->plane = plane;
      }
示例#26
0
arlCore::Tag::Tag( PlaneSystem &universe, PointList::csptr pl ):
//VAG Object(arlCore::ARLCORE_CLASS_TAG, "Points cloud"),
Particle( universe, "Points cloud" ),
Parameters("Tag"),
m_geometry( PointList::New() ),
m_measures( PointList::New() ),
m_measuresPlane( 0 ),
m_registrationType( ARLCORE_TAG_REGISTRATION_3D3D ),
m_registrationMaxError(-1.0),
m_persistence(-1)
{
    init();
    arlCore::Point::sptr p0 = arlCore::Point::New(0.0, 0.0, 0.0);
    p0->setVisible(false);
    unsigned int i;
    for(i=0 ; i<pl->size() ; ++i)
    {
        m_geometry->push_back( (*pl)[i] );
        m_measures->push_back(p0);
    }
    getPlaneSystem().setPlaneName(getPlane(), Object::getName());
    //VAG FIXME setOK();
}
示例#27
0
    void channelNormalization(Mat &srcBlob, Mat &dstBlob)
    {
        int num = srcBlob.size[0];
        int channels = srcBlob.size[1];
        int ksize = (size - 1) / 2;
        int sizeNormFactor = normBySize ? size : 1;

        Mat srcMat = srcBlob.clone();
        Mat dstMat = dstBlob;

        for (int n = 0; n < num; n++)
        {
            Mat accum = getPlane(dstMat, n, channels-1); //trick for memory saving
            accum.setTo(0);

            for (int cn = 0; cn < std::min(ksize, channels); cn++)
                cv::accumulateSquare(getPlane(srcMat, n, cn), accum);

            for (int cn = 0; cn < channels; cn++)
            {
                if (cn + ksize < channels)
                {
                    cv::accumulateSquare(getPlane(srcMat, n, cn + ksize), accum);
                }

                if (cn - ksize - 1 >= 0)
                {
                    //subtractSquare
                    Mat left = getPlane(srcMat, n, cn - ksize - 1);
                    cv::pow(left, 2, left);
                    cv::subtract(accum, left, accum);
                }

                Mat dst = getPlane(dstMat, n, cn);
                accum.convertTo(dst, dst.type(), alpha/sizeNormFactor, bias);
                cv::pow(dst, beta, dst);
                cv::divide(getPlane(srcMat, n, cn), dst, dst);
            }
        }
    }
示例#28
0
文件: AABox.cpp 项目: Issacchaos/hifi
glm::vec3 AABox::getClosestPointOnFace(const glm::vec4& origin, const glm::vec4& direction, BoxFace face) const {
    // check against the four planes that border the face
    BoxFace oppositeFace = getOppositeFace(face);
    bool anyOutside = false;
    for (int i = 0; i < FACE_COUNT; i++) {
        if (i == face || i == oppositeFace) {
            continue;
        }
        glm::vec4 iPlane = getPlane((BoxFace)i);
        float originDistance = glm::dot(origin, iPlane);
        if (originDistance < 0.0f) {
            continue; // inside the border
        }
        anyOutside = true;
        float divisor = glm::dot(direction, iPlane);
        if (fabs(divisor) < EPSILON) {
            continue; // segment is parallel to plane
        }
        // find intersection and see if it lies within face bounds
        float directionalDistance = -originDistance / divisor;
        glm::vec4 intersection = origin + direction * directionalDistance;
        BoxFace iOppositeFace = getOppositeFace((BoxFace)i);
        for (int j = 0; j < FACE_COUNT; j++) {
            if (j == face || j == oppositeFace || j == i || j == iOppositeFace) {
                continue;
            }
            if (glm::dot(intersection, getPlane((BoxFace)j)) > 0.0f) {
                goto outerContinue; // intersection is out of bounds
            }
        }
        return getClosestPointOnFace(glm::vec3(intersection), face);
        
        outerContinue: ;
    }
    
    // if we were outside any of the sides, we must check against the diagonals
    if (anyOutside) {
        int faceAxis = face / 2;
        int secondAxis = (faceAxis + 1) % 3;
        int thirdAxis = (faceAxis + 2) % 3;
        
        glm::vec4 secondAxisMinPlane = getPlane((BoxFace)(secondAxis * 2));
        glm::vec4 secondAxisMaxPlane = getPlane((BoxFace)(secondAxis * 2 + 1));
        glm::vec4 thirdAxisMaxPlane = getPlane((BoxFace)(thirdAxis * 2 + 1));
        
        glm::vec4 offset = glm::vec4(0.0f, 0.0f, 0.0f,
            glm::dot(glm::vec3(secondAxisMaxPlane + thirdAxisMaxPlane), glm::vec3(_scale, _scale, _scale)) * 0.5f);
        glm::vec4 diagonals[] = { secondAxisMinPlane + thirdAxisMaxPlane + offset,
            secondAxisMaxPlane + thirdAxisMaxPlane + offset };
        
        float minDistance = FLT_MAX;
        for (int i = 0; i < sizeof(diagonals) / sizeof(diagonals[0]); i++) {
            float divisor = glm::dot(direction, diagonals[i]);
            if (fabs(divisor) < EPSILON) {
                continue; // segment is parallel to diagonal plane
            }
            minDistance = glm::min(-glm::dot(origin, diagonals[i]) / divisor, minDistance);
        }
        if (minDistance != FLT_MAX) {
            return getClosestPointOnFace(glm::vec3(origin + direction * minDistance), face);
        }
    }
    
    // last resort or all inside: clamp origin to face
    return getClosestPointOnFace(glm::vec3(origin), face);
}
示例#29
0
void BruntonPrimitive::buildBrunton(void)
	{
	/* Create the root node: */
	SceneGraph::TransformNode* rootT=new SceneGraph::TransformNode;
	root=rootT;
	getSceneGraphRoot().children.appendValue(root);
	getSceneGraphRoot().update();
	
	/* Calculate the plane primitive's centroid: */
	Point::AffineCombiner cc;
	for(int i=0;i<4;++i)
		cc.addPoint(getPoint(i));
	Point centroid=cc.getPoint();
	Scalar bruntonScale=Math::mid(Geometry::dist(getPoint(2),getPoint(0)),Geometry::dist(getPoint(3),getPoint(1)));
	
	/* Calculate the plane primitive's dip angle and strike vector: */
	Vector normal=getPlane().getNormal();
	if(normal[2]<Scalar(0))
		normal=-normal;
	normal.normalize();
	Vector strike=normal;
	Scalar dipAngle=Math::acos(strike[2]/Geometry::mag(strike));
	strike[2]=Scalar(0);
	strike.normalize();
	Scalar strikeAngle=Math::atan2(-strike[0],strike[1]);
	
	/* Set the root node's transformation: */
	rootT->translation.setValue(centroid-Point::origin);
	
	/* Create the dip and strike indicator: */
	SceneGraph::ShapeNode* s1=new SceneGraph::ShapeNode;
	rootT->children.appendValue(s1);
	{
	SceneGraph::IndexedLineSetNode* ils=new SceneGraph::IndexedLineSetNode;
	s1->geometry.setValue(ils);
	
	SceneGraph::ColorNode* color=new SceneGraph::ColorNode;
	ils->color.setValue(color);
	color->color.appendValue(SceneGraph::Color(0.0f,0.5f,1.0f));
	color->color.appendValue(SceneGraph::Color(0.0f,1.0f,0.5f));
	color->update();
	
	SceneGraph::CoordinateNode* coord=new SceneGraph::CoordinateNode;
	ils->coord.setValue(coord);
	coord->point.appendValue(Point::origin);
	coord->point.appendValue(Point::origin+normal*bruntonScale);
	coord->point.appendValue(Point::origin+strike*bruntonScale);
	coord->update();
	
	ils->coordIndex.appendValue(0);
	ils->coordIndex.appendValue(1);
	ils->coordIndex.appendValue(-1);
	ils->coordIndex.appendValue(0);
	ils->coordIndex.appendValue(2);
	
	ils->colorPerVertex.setValue(false);
	ils->lineWidth.setValue(3.0f);
	ils->update();
	}
	s1->update();
	
	SceneGraph::ShapeNode* s2=new SceneGraph::ShapeNode;
	rootT->children.appendValue(s2);
	{
	SceneGraph::IndexedLineSetNode* ils=new SceneGraph::IndexedLineSetNode;
	s2->geometry.setValue(ils);
	
	SceneGraph::ColorNode* color=new SceneGraph::ColorNode;
	ils->color.setValue(color);
	color->color.appendValue(SceneGraph::Color(0.0f,0.5f,1.0f));
	color->color.appendValue(SceneGraph::Color(0.0f,0.5f,1.0f));
	color->color.appendValue(SceneGraph::Color(0.0f,1.0f,0.5f));
	color->color.appendValue(SceneGraph::Color(0.0f,1.0f,0.5f));
	color->update();
	
	SceneGraph::CoordinateNode* coord=new SceneGraph::CoordinateNode;
	ils->coord.setValue(coord);
	
	coord->point.appendValue(Point::origin);
	coord->point.appendValue(Point(0,0,bruntonScale));
	coord->point.appendValue(Point(0,bruntonScale,0));
	ils->coordIndex.appendValue(0);
	ils->coordIndex.appendValue(1);
	ils->coordIndex.appendValue(-1);
	for(Scalar a=Scalar(0);a<dipAngle;a+=Math::rad(Scalar(10)))
		{
		ils->coordIndex.appendValue(coord->point.getNumValues());
		coord->point.appendValue(Point::origin+(Vector(0,0,1)*Math::cos(a)+strike*Math::sin(a))*(bruntonScale*Scalar(0.9)));
		}
	ils->coordIndex.appendValue(coord->point.getNumValues());
	coord->point.appendValue(Point::origin+(Vector(0,0,1)*Math::cos(dipAngle)+strike*Math::sin(dipAngle))*(bruntonScale*Scalar(0.9)));
	ils->coordIndex.appendValue(-1);
	
	ils->coordIndex.appendValue(0);
	ils->coordIndex.appendValue(2);
	ils->coordIndex.appendValue(-1);
	Scalar aInc=Math::rad(Scalar(10));
	if(strikeAngle<Scalar(0))
		aInc=-aInc;
	for(Scalar a=Scalar(0);Math::abs(a)<Math::abs(strikeAngle);a+=aInc)
		{
		ils->coordIndex.appendValue(coord->point.getNumValues());
		coord->point.appendValue(Point::origin+Vector(-Math::sin(a),Math::cos(a),0)*(bruntonScale*Scalar(0.9)));
		}
	ils->coordIndex.appendValue(coord->point.getNumValues());
	coord->point.appendValue(Point::origin+Vector(-Math::sin(strikeAngle),Math::cos(strikeAngle),0)*(bruntonScale*Scalar(0.9)));
	
	coord->update();
	
	ils->colorPerVertex.setValue(false);
	ils->lineWidth.setValue(1.0f);
	ils->update();
	}
	s2->update();
	
	SceneGraph::TransformNode* t2=new SceneGraph::TransformNode;
	rootT->children.appendValue(t2);
	t2->translation.setValue((Vector(0,0,1)*Math::cos(Math::div2(dipAngle))+strike*Math::sin(Math::div2(dipAngle)))*bruntonScale);
	{
	SceneGraph::BillboardNode* bb=new SceneGraph::BillboardNode;
	t2->children.appendValue(bb);
	bb->axisOfRotation.setValue(Vector::zero);
	{
	SceneGraph::ShapeNode* s=new SceneGraph::ShapeNode;
	bb->children.appendValue(s);
	
	SceneGraph::TextNode* text=new SceneGraph::TextNode;
	s->geometry.setValue(text);
	
	SceneGraph::FontStyleNode* fs=new SceneGraph::FontStyleNode;
	text->fontStyle.setValue(fs);
	fs->size.setValue(bruntonScale*Scalar(0.25));
	fs->justify.appendValue("MIDDLE");
	fs->justify.appendValue("MIDDLE");
	
	fs->update();
	
	char buffer[40];
	snprintf(buffer,sizeof(buffer),"%.2f",Math::deg(dipAngle));
	text->string.appendValue(buffer);
	text->update();
	
	s->update();
	}
	bb->update();
	}
	t2->update();
	
	SceneGraph::TransformNode* t3=new SceneGraph::TransformNode;
	rootT->children.appendValue(t3);
	t3->translation.setValue(Vector(-Math::sin(Math::div2(strikeAngle)),Math::cos(Math::div2(strikeAngle)),0)*bruntonScale);
	{
	SceneGraph::BillboardNode* bb=new SceneGraph::BillboardNode;
	t3->children.appendValue(bb);
	bb->axisOfRotation.setValue(Vector::zero);
	{
	SceneGraph::ShapeNode* s=new SceneGraph::ShapeNode;
	bb->children.appendValue(s);
	
	SceneGraph::TextNode* text=new SceneGraph::TextNode;
	s->geometry.setValue(text);
	
	SceneGraph::FontStyleNode* fs=new SceneGraph::FontStyleNode;
	text->fontStyle.setValue(fs);
	fs->size.setValue(bruntonScale*Scalar(0.25));
	fs->justify.appendValue("MIDDLE");
	fs->justify.appendValue("MIDDLE");
	
	fs->update();
	
	char buffer[40];
	Scalar sa=-Math::deg(strikeAngle);
	if(sa<Scalar(0))
		sa+=360.0;
	snprintf(buffer,sizeof(buffer),"%.2f",sa);
	text->string.appendValue(buffer);
	text->update();
	
	s->update();
	}
	bb->update();
	}
	t3->update();
	
	rootT->update();
	}
示例#30
0
/******************************************************************
Function    : void NPC::spawnEnemy()
Date        : 2015-11-13 14:13:03
Author      : Quinn Pan
Parameter   : 
Return      : 
Desc        : Spawn an enemy
******************************************************************/
void NPC::spawnEnemy()
{
    //log("refresh an enemy");

    auto winSize = Director::getInstance()->getWinSize();

    int enemy_type = PlaneEnemy::Enemy1;

    //根据游戏Level选择性随机刷新不同种类的战机
    switch (m_level)
    {
    case GameScene::LEVEL1:
        break;
    case GameScene::LEVEL2:
        enemy_type = random(0, 1);
        break;
    case GameScene::LEVEL3:
        enemy_type = random(0, 2);
        if (m_canBossRefresh && enemy_type == 2) //如果刷新出boss战机,那么禁止其继续刷新,直到该禁止标志被重置
            m_canBossRefresh = false;
        else enemy_type = random(0, 1);
        break;
    case GameScene::LEVEL4:
        enemy_type = random(0, 3);
        if (m_canBossRefresh && enemy_type >= 2)
            m_canBossRefresh = false;
        else enemy_type = random(0, 1);
        break;
    case GameScene::LEVEL5:
        enemy_type = random(0, 3);
        if (m_canBossRefresh && enemy_type >= 2)
            m_canBossRefresh = false;
        else enemy_type = random(0, 1);
        break;
    }

    auto enemy = behaviac::Agent::Create<Enemy>();
    enemy->createAnEnemyWithType(enemy_type);
    ////根据战机类型加入战机
    PlaneEnemy* enemy_plane = enemy->getPlane();
    ((Node*)this->getParent())->addChild(enemy_plane, 0, GameScene::ENEMY_TAG);
    //behaviac::Agent::Destroy(enemy);

    //enemy->SetActive(false);
    //enemy_plane1->setColor(Color3B(255, 0, 255));

    //auto enemy_plane = PlaneEnemy::createWithEnemyType(enemy_type);
    //((Node*)this->getParent())->addChild(enemy_plane, 0, GameScene::ENEMY_TAG);

    //设定战机初始位置的X轴的取值范围,根据这个范围随机设置战机初始X轴位置
    int min = enemy_plane->getContentSize().width / 2;
    int max = winSize.width - enemy_plane->getContentSize().width / 2;
    enemy_plane->setPosition(Vec2(random(min, max), winSize.height + enemy_plane->getContentSize().height / 2));

    //给敌机一个body
    Vec2 vec[10]; //存放敌方战机的多边形点
    memset(vec, 0, sizeof(vec));
    int vec_count = 0;
    switch (enemy_type)
    {
    case PlaneEnemy::Enemy1:
        vec[0] = Vec2(0, -18);
        vec[1] = Vec2(-24, 6);
        vec[2] = Vec2(24, 6);
        vec_count = 3;
        break;
    case PlaneEnemy::Enemy2:
        vec[0] = Vec2(0, -40);
        vec[1] = Vec2(-40, 0);
        vec[2] = Vec2(0, 45);
        vec[3] = Vec2(40, 0);
        vec_count = 4;
        break;
    default:
        vec[0] = Vec2(35, -120);
        vec[1] = Vec2(-35, -120);
        vec[2] = Vec2(-80, -88);
        vec[3] = Vec2(-80, 130);
        vec[4] = Vec2(80, 130);
        vec[5] = Vec2(80, -88);
        vec_count = 6;
        break;
    }
    //auto enemybody = PhysicsBody::createBox(enemy_plane->getContentSize());
    auto enemybody = PhysicsBody::create();
    enemybody->addShape(PhysicsShapePolygon::create(vec, vec_count));
    enemybody->setCollisionBitmask(0x0); //不进行碰撞模拟,因为不需要
    enemybody->setContactTestBitmask(GameScene::ENEMY_CONTACTMASKBIT);
    enemy_plane->setPhysicsBody(enemybody);
}