LimitStencilTables const *
LimitStencilTablesFactory::Create(TopologyRefiner const & refiner,
    LocationArrayVec const & locationArrays, StencilTables const * cvStencils,
        PatchTables const * patchTables) {

    // Compute the total number of stencils to generate
    int numStencils=0, numLimitStencils=0;
    for (int i=0; i<(int)locationArrays.size(); ++i) {
        assert(locationArrays[i].numLocations>=0);
        numStencils += locationArrays[i].numLocations;
    }
    if (numStencils<=0) {
        return 0;
    }

    bool uniform = refiner.IsUniform();

    int maxlevel = refiner.GetMaxLevel(), maxsize=17;

    StencilTables const * cvstencils = cvStencils;
    if (not cvstencils) {
        // Generate stencils for the control vertices - this is necessary to
        // properly factorize patches with control vertices at level 0 (natural
        // regular patches, such as in a torus)
        // note: the control vertices of the mesh are added as single-index
        //       stencils of weight 1.0f
        StencilTablesFactory::Options options;
        options.generateIntermediateLevels = uniform ? false :true;
        options.generateControlVerts = true;
        options.generateOffsets = true;

        // XXXX (manuelk) We could potentially save some mem-copies by not
        // instanciating the stencil tables and work directly off the pool
        // allocators.
        cvstencils = StencilTablesFactory::Create(refiner, options);
    } else {
        // Sanity checks
        if (cvstencils->GetNumStencils() != (uniform ?
            refiner.GetNumVertices(maxlevel) :
                refiner.GetNumVerticesTotal())) {
                return 0;
        }
    }

    // If a stencil table was given, use it, otherwise, create a new one
    PatchTables const * patchtables = patchTables;
    if (not patchTables) {
        // XXXX (manuelk) If no patch-tables was passed, we should be able to
        // infer the patches fairly easily from the refiner. Once more tags
        // have been added to the refiner, maybe we can remove the need for the
        // patch tables.

        OpenSubdiv::Far::PatchTablesFactory::Options options;
        options.adaptiveStencilTables = cvstencils;

        patchtables = PatchTablesFactory::Create(refiner, options);
    } else {
        // Sanity checks
        if (patchTables->IsFeatureAdaptive()==uniform) {
            if (not cvStencils) {
                assert(cvstencils and cvstencils!=cvStencils);
                delete cvstencils;
            }
            return 0;
        }
    }

    assert(patchtables and cvstencils);

    // Create a patch-map to locate sub-patches faster
    PatchMap patchmap( *patchtables );

    //
    // Generate limit stencils for locations
    //

    // Create a pool allocator to accumulate ProtoLimitStencils
    LimitStencilAllocator alloc(maxsize);
    alloc.Resize(numStencils);

    // XXXX (manuelk) we can make uniform (bilinear) stencils faster with a
    //       dedicated code path that does not use PatchTables or the PatchMap
    for (int i=0, currentStencil=0; i<(int)locationArrays.size(); ++i) {

        LocationArray const & array = locationArrays[i];

        assert(array.ptexIdx>=0);

        for (int j=0; j<array.numLocations; ++j, ++currentStencil) {

            float s = array.s[j],
                  t = array.t[j];

            PatchMap::Handle const * handle =
                patchmap.FindPatch(array.ptexIdx, s, t);

            if (handle) {
                ProtoLimitStencil dst = alloc[currentStencil];
                if (uniform) {
                    patchtables->Interpolate(*handle, s, t, *cvstencils, dst);
                } else {
                    patchtables->Limit(*handle, s, t, *cvstencils, dst);
                }
                ++numLimitStencils;
            }
        }
    }

    if (not cvStencils) {
        delete cvstencils;
    }

    //
    // Copy the proto-stencils into the limit stencil tables
    //
    LimitStencilTables * result = new LimitStencilTables;

    int nelems = alloc.GetNumVerticesTotal();
    if (nelems>0) {

        // Allocate
        result->resize(numLimitStencils, nelems);

        // Copy stencils
        LimitStencil dst(&result->_sizes.at(0), &result->_indices.at(0),
            &result->_weights.at(0), &result->_duWeights.at(0),
                &result->_dvWeights.at(0));

        for (int i=0; i<alloc.GetNumStencils(); ++i) {
            *dst._size = alloc.CopyLimitStencil(i, dst._indices, dst._weights,
                dst._duWeights, dst._dvWeights);
            dst.Next();
        }

        // XXXX manuelk should offset creation be optional ?
        result->generateOffsets();
    }
    result->_numControlVertices = refiner.GetNumVertices(0);

    return result;
}
Example #2
0
int Timezone::tzd()
{
	return utcOffset() + dst();
}
sk_sp<SkSpecialImage> SkXfermodeImageFilter::filterImageGPU(SkSpecialImage* source,
                                                            sk_sp<SkSpecialImage> background,
                                                            const SkIPoint& backgroundOffset,
                                                            sk_sp<SkSpecialImage> foreground,
                                                            const SkIPoint& foregroundOffset,
                                                            const SkIRect& bounds) const {
    SkASSERT(source->isTextureBacked());

    GrContext* context = source->getContext();

    sk_sp<GrTexture> backgroundTex, foregroundTex;
    
    if (background) {
        backgroundTex.reset(background->asTextureRef(context));
    }

    if (foreground) {
        foregroundTex.reset(foreground->asTextureRef(context));
    }

    GrSurfaceDesc desc;
    desc.fFlags = kRenderTarget_GrSurfaceFlag;
    desc.fWidth = bounds.width();
    desc.fHeight = bounds.height();
    desc.fConfig = kSkia8888_GrPixelConfig;
    SkAutoTUnref<GrTexture> dst(context->textureProvider()->createApproxTexture(desc));
    if (!dst) {
        return nullptr;
    }

    GrPaint paint;
    // SRGBTODO: AllowSRGBInputs?
    SkAutoTUnref<const GrFragmentProcessor> bgFP;

    if (backgroundTex) {
        SkMatrix backgroundMatrix;
        backgroundMatrix.setIDiv(backgroundTex->width(), backgroundTex->height());
        backgroundMatrix.preTranslate(SkIntToScalar(-backgroundOffset.fX),
                                      SkIntToScalar(-backgroundOffset.fY));
        bgFP.reset(GrTextureDomainEffect::Create(
                            backgroundTex.get(), backgroundMatrix,
                            GrTextureDomain::MakeTexelDomain(backgroundTex.get(),
                                                             background->subset()),
                            GrTextureDomain::kDecal_Mode,
                            GrTextureParams::kNone_FilterMode));
    } else {
        bgFP.reset(GrConstColorProcessor::Create(GrColor_TRANSPARENT_BLACK,
                                                 GrConstColorProcessor::kIgnore_InputMode));
    }

    if (foregroundTex) {
        SkMatrix foregroundMatrix;
        foregroundMatrix.setIDiv(foregroundTex->width(), foregroundTex->height());
        foregroundMatrix.preTranslate(SkIntToScalar(-foregroundOffset.fX),
                                      SkIntToScalar(-foregroundOffset.fY));

        SkAutoTUnref<const GrFragmentProcessor> foregroundFP;

        foregroundFP.reset(GrTextureDomainEffect::Create(
                            foregroundTex.get(), foregroundMatrix,
                            GrTextureDomain::MakeTexelDomain(foregroundTex.get(), 
                                                             foreground->subset()),
                            GrTextureDomain::kDecal_Mode,
                            GrTextureParams::kNone_FilterMode));

        paint.addColorFragmentProcessor(foregroundFP.get());

        // A null fMode is interpreted to mean kSrcOver_Mode (to match raster).
        SkAutoTUnref<SkXfermode> mode(SkSafeRef(fMode.get()));
        if (!mode) {
            // It would be awesome to use SkXfermode::Create here but it knows better
            // than us and won't return a kSrcOver_Mode SkXfermode. That means we
            // have to get one the hard way.
            struct ProcCoeff rec;
            rec.fProc = SkXfermode::GetProc(SkXfermode::kSrcOver_Mode);
            SkXfermode::ModeAsCoeff(SkXfermode::kSrcOver_Mode, &rec.fSC, &rec.fDC);

            mode.reset(new SkProcCoeffXfermode(rec, SkXfermode::kSrcOver_Mode));
        }

        SkAutoTUnref<const GrFragmentProcessor> xferFP(mode->getFragmentProcessorForImageFilter(bgFP));

        // A null 'xferFP' here means kSrc_Mode was used in which case we can just proceed
        if (xferFP) {
            paint.addColorFragmentProcessor(xferFP);
        }
    } else {
        paint.addColorFragmentProcessor(bgFP);
    }

    paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);

    SkAutoTUnref<GrDrawContext> drawContext(context->drawContext(dst->asRenderTarget()));
    if (!drawContext) {
        return nullptr;
    }

    SkMatrix matrix;
    matrix.setTranslate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top()));
    drawContext->drawRect(GrClip::WideOpen(), paint, matrix, SkRect::Make(bounds));

    return SkSpecialImage::MakeFromGpu(SkIRect::MakeWH(bounds.width(), bounds.height()),
                                       kNeedNewImageUniqueID_SpecialImage,
                                       dst.get());
}
void VideoVisualGoom::Draw(const QRect &area, MythPainter */*painter*/,
                           QPaintDevice */*device*/)
{
    if (m_disabled || !m_render || area.isEmpty())
        return;

    QMutexLocker lock(mutex());
    unsigned int* last = m_buffer;
    VisualNode *node = GetNode();
    if (node)
    {
        int numSamps = 512;
        if (node->length < 512)
            numSamps = node->length;

        signed short int data[2][512];
        int i= 0;
        for (; i < numSamps; i++)
        {
            data[0][i] = node->left[i];
            data[1][i] = node->right ? node->right[i] : data[0][i];
        }

        for (; i < 512; i++)
        {
            data[0][i] = 0;
            data[1][i] = 0;
        }

        m_buffer = goom_update(data, 0);
    }

#ifdef USING_OPENGL
    if ((m_render->Type() == kRenderOpenGL1) ||
        (m_render->Type() == kRenderOpenGL2) ||
        (m_render->Type() == kRenderOpenGL2ES))
    {
        MythRenderOpenGL *glrender =
                    static_cast<MythRenderOpenGL*>(m_render);
        if (!m_surface && glrender && m_buffer)
        {
            m_surface = glrender->CreateTexture(m_area.size(),
                                  glrender->GetFeatures() & kGLExtPBufObj, 0,
                                  GL_UNSIGNED_BYTE, GL_RGBA, GL_RGBA8,
                                  GL_LINEAR_MIPMAP_LINEAR);
        }

        if (m_surface && glrender && m_buffer)
        {
            if (m_buffer != last)
            {
                bool copy = glrender->GetFeatures() & kGLExtPBufObj;
                void* buf = glrender->GetTextureBuffer(m_surface, copy);
                if (copy)
                    memcpy(buf, m_buffer, m_area.width() * m_area.height() * 4);
                glrender->UpdateTexture(m_surface, (void*)m_buffer);
            }
            QRectF src(m_area);
            QRectF dst(area);
            glrender->DrawBitmap(&m_surface, 1, 0, &src, &dst, 0);
        }
        return;
    }
#endif

#ifdef USING_VDPAU
    if (m_render->Type() == kRenderVDPAU)
    {
        MythRenderVDPAU *render =
                    static_cast<MythRenderVDPAU*>(m_render);

        if (!m_surface && render)
            m_surface = render->CreateBitmapSurface(m_area.size());

        if (m_surface && render && m_buffer)
        {
            if (m_buffer != last)
            {
                void    *plane[1] = { m_buffer };
                uint32_t pitch[1] = { static_cast<uint32_t>(m_area.width() * 4) };
                render->UploadBitmap(m_surface, plane, pitch);
            }
            render->DrawBitmap(m_surface, 0, nullptr, nullptr, kVDPBlendNull, 255, 255, 255, 255);
        }
        return;
    }
#endif
}
Example #5
0
void Arc::render( wxDC& dc ) const
{
    dc.SetPen( wxPen( getColour(), Model::TWIPS ) );
    dc.DrawLine( src(), dst() );
    arrowHead( dc, src(), dst() );
}
bool SkDisplacementMapEffect::filterImageGPU(Proxy* proxy, const SkBitmap& src, const Context& ctx,
                                             SkBitmap* result, SkIPoint* offset) const {
    SkBitmap colorBM = src;
    SkIPoint colorOffset = SkIPoint::Make(0, 0);
    if (!this->filterInputGPU(1, proxy, src, ctx, &colorBM, &colorOffset)) {
        return false;
    }
    SkBitmap displacementBM = src;
    SkIPoint displacementOffset = SkIPoint::Make(0, 0);
    if (!this->filterInputGPU(0, proxy, src, ctx, &displacementBM, &displacementOffset)) {
        return false;
    }
    SkIRect srcBounds = colorBM.bounds();
    srcBounds.offset(colorOffset);
    SkIRect bounds;
    // Since GrDisplacementMapEffect does bounds checking on color pixel access, we don't need to
    // pad the color bitmap to bounds here.
    if (!this->applyCropRect(ctx, srcBounds, &bounds)) {
        return false;
    }
    SkIRect displBounds;
    if (!this->applyCropRect(ctx, proxy, displacementBM,
                             &displacementOffset, &displBounds, &displacementBM)) {
        return false;
    }
    if (!bounds.intersect(displBounds)) {
        return false;
    }
    GrTexture* color = colorBM.getTexture();
    GrTexture* displacement = displacementBM.getTexture();
    GrContext* context = color->getContext();

    GrSurfaceDesc desc;
    desc.fFlags = kRenderTarget_GrSurfaceFlag;
    desc.fWidth = bounds.width();
    desc.fHeight = bounds.height();
    desc.fConfig = kSkia8888_GrPixelConfig;

    SkAutoTUnref<GrTexture> dst(context->textureProvider()->createApproxTexture(desc));

    if (!dst) {
        return false;
    }

    SkVector scale = SkVector::Make(fScale, fScale);
    ctx.ctm().mapVectors(&scale, 1);

    GrPaint paint;
    SkMatrix offsetMatrix = GrCoordTransform::MakeDivByTextureWHMatrix(displacement);
    offsetMatrix.preTranslate(SkIntToScalar(colorOffset.fX - displacementOffset.fX),
                              SkIntToScalar(colorOffset.fY - displacementOffset.fY));

    paint.addColorFragmentProcessor(
        GrDisplacementMapEffect::Create(fXChannelSelector,
                                        fYChannelSelector,
                                        scale,
                                        displacement,
                                        offsetMatrix,
                                        color,
                                        colorBM.dimensions()))->unref();
    paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
    SkIRect colorBounds = bounds;
    colorBounds.offset(-colorOffset);
    SkMatrix matrix;
    matrix.setTranslate(-SkIntToScalar(colorBounds.x()),
                        -SkIntToScalar(colorBounds.y()));

    SkAutoTUnref<GrDrawContext> drawContext(context->drawContext(dst->asRenderTarget()));
    if (!drawContext) {
        return false;
    }

    drawContext->drawRect(GrClip::WideOpen(), paint, matrix, SkRect::Make(colorBounds));
    offset->fX = bounds.left();
    offset->fY = bounds.top();
    GrWrapTextureInBitmap(dst, bounds.width(), bounds.height(), false, result);
    return true;
}
Example #7
0
	jobject get( JNIEnv* env, VARIANT* v, jclass retType ) {
		_variant_t dst(v);
		dst.ChangeType(VT_DATE);
		return com4j_Variant_toDate(env,dst.date);
	}
Example #8
0
extern "C" Lz4MtResult
lz4mtCompress(Lz4MtContext* lz4MtContext, const Lz4MtStreamDescriptor* sd)
{
	assert(lz4MtContext);
	assert(sd);

	Context ctx_(lz4MtContext);
	Context* ctx = &ctx_;

	{
		char d[LZ4S_MAX_HEADER_SIZE] = { 0 };
		auto p = &d[0];

		const auto r = validateStreamDescriptor(sd);
		if(LZ4MT_RESULT_OK != r) {
			return ctx->setResult(r);
		}
		p += storeU32(p, LZ4S_MAGICNUMBER);

		const auto* sumBegin = p;
		*p++ = flgToChar(sd->flg);
		*p++ = bdToChar(sd->bd);
		if(sd->flg.streamSize) {
			assert(sd->streamSize);
			p += storeU64(p, sd->streamSize);
		}
		if(sd->flg.presetDictionary) {
			p += storeU32(p, sd->dictId);
		}

		const auto sumSize = static_cast<int>(p - sumBegin);
		const auto h = Lz4Mt::Xxh32(sumBegin, sumSize, LZ4S_CHECKSUM_SEED).digest();
		*p++ = static_cast<char>(getCheckBits_FromXXH(h));
		assert(p <= std::end(d));

		const auto writeSize = static_cast<int>(p - d);
		if(writeSize != ctx->write(d, writeSize)) {
			return ctx->setResult(LZ4MT_RESULT_CANNOT_WRITE_HEADER);
		}
	}

	const auto nBlockMaximumSize = getBlockSize(sd->bd.blockMaximumSize);
	const auto nBlockSize        = 4;
	const auto nBlockCheckSum    = sd->flg.blockChecksum ? 4 : 0;
	const auto cIncompressible   = 1 << (nBlockSize * 8 - 1);
	const bool streamChecksum    = 0 != sd->flg.streamChecksum;
	const bool singleThread      = 0 != (ctx->mode() & LZ4MT_MODE_SEQUENTIAL);
	const auto nConcurrency      = Lz4Mt::getHardwareConcurrency();
	const auto nPool             = singleThread ? 1 : nConcurrency + 1;
	const auto launch            = singleThread ? Lz4Mt::launch::deferred : std::launch::async;

	Lz4Mt::MemPool srcBufferPool(nBlockMaximumSize, nPool);
	Lz4Mt::MemPool dstBufferPool(nBlockMaximumSize, nPool);
	std::vector<std::future<void>> futures;
	Lz4Mt::Xxh32 xxhStream(LZ4S_CHECKSUM_SEED);

	const auto f =
		[&futures, &dstBufferPool, &xxhStream
		 , ctx, nBlockCheckSum, streamChecksum, launch, cIncompressible
		 ]
		(int i, Lz4Mt::MemPool::Buffer* srcRawPtr, int srcSize)
	{
		BufferPtr src(srcRawPtr);
		if(ctx->error()) {
			return;
		}

		const auto* srcPtr = src->data();
		BufferPtr dst(dstBufferPool.alloc());
		auto* cmpPtr = dst->data();
		const auto cmpSize = ctx->compress(srcPtr, cmpPtr, srcSize, srcSize);
		const bool incompressible = (cmpSize <= 0);
		const auto* cPtr  = incompressible ? srcPtr  : cmpPtr;
		const auto  cSize = incompressible ? srcSize : cmpSize;

		std::future<uint32_t> futureBlockHash;
		if(nBlockCheckSum) {
			futureBlockHash = std::async(launch, [=] {
				return Lz4Mt::Xxh32(cPtr, cSize, LZ4S_CHECKSUM_SEED).digest();
			});
		}

		if(incompressible) {
			dst.reset();
		}

		if(i > 0) {
			futures[i-1].wait();
		}

		std::future<void> futureStreamHash;
		if(streamChecksum) {
			futureStreamHash = std::async(launch, [=, &xxhStream] {
				xxhStream.update(srcPtr, srcSize);
			});
		}

		if(incompressible) {
			ctx->writeU32(cSize | cIncompressible);
			ctx->writeBin(srcPtr, srcSize);
		} else {
			ctx->writeU32(cSize);
			ctx->writeBin(cmpPtr, cmpSize);
		}

		if(futureBlockHash.valid()) {
			ctx->writeU32(futureBlockHash.get());
		}

		if(futureStreamHash.valid()) {
			futureStreamHash.wait();
		}
	};

	for(int i = 0;; ++i) {
		BufferPtr src(srcBufferPool.alloc());
		auto* srcPtr = src->data();
		const auto srcSize = src->size();
		const auto readSize = ctx->read(srcPtr, static_cast<int>(srcSize));

		if(0 == readSize) {
			break;
		}

		if(singleThread) {
			f(0, src.release(), readSize);
		} else {
			futures.emplace_back(std::async(launch, f, i, src.release(), readSize));
		}
	}

	for(auto& e : futures) {
		e.wait();
	}

	if(!ctx->writeU32(LZ4S_EOS)) {
		return LZ4MT_RESULT_CANNOT_WRITE_EOS;
	}

	if(streamChecksum) {
		const auto digest = xxhStream.digest();
		if(!ctx->writeU32(digest)) {
			return LZ4MT_RESULT_CANNOT_WRITE_STREAM_CHECKSUM;
		}
	}

	return LZ4MT_RESULT_OK;
}
Example #9
0
extern "C" Lz4MtResult
lz4mtDecompress(Lz4MtContext* lz4MtContext, Lz4MtStreamDescriptor* sd)
{
	assert(lz4MtContext);
	assert(sd);

	Context ctx_(lz4MtContext);
	Context* ctx = &ctx_;

	std::atomic<bool> quit(false);

	ctx->setResult(LZ4MT_RESULT_OK);
	while(!quit && !ctx->error() && !ctx->readEof()) {
		const auto magic = ctx->readU32();
		if(ctx->error()) {
			if(ctx->readEof()) {
				ctx->setResult(LZ4MT_RESULT_OK);
			} else {
				ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
			}
			break;
		}

		if(isSkippableMagicNumber(magic)) {
			const auto size = ctx->readU32();
			if(ctx->error()) {
				ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
				break;
			}
			const auto s = ctx->readSkippable(magic, size);
			if(s < 0 || ctx->error()) {
				ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
				break;
			}
			continue;
		}

		if(LZ4S_MAGICNUMBER != magic) {
			ctx->readSeek(-4);
			ctx->setResult(LZ4MT_RESULT_INVALID_MAGIC_NUMBER);
			break;
		}

		char d[LZ4S_MAX_HEADER_SIZE] = { 0 };
		auto* p = d;
		const auto* sumBegin = p;

		if(2 != ctx->read(p, 2)) {
			ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
			break;
		}
		sd->flg = charToFlg(*p++);
		sd->bd  = charToBc(*p++);
		const auto r = validateStreamDescriptor(sd);
		if(LZ4MT_RESULT_OK != r) {
			ctx->setResult(r);
			break;
		}

		const int nExInfo =
			  (sd->flg.streamSize       ? sizeof(uint64_t) : 0)
			+ (sd->flg.presetDictionary ? sizeof(uint32_t) : 0)
			+ 1
		;
		if(nExInfo != ctx->read(p, nExInfo)) {
			ctx->setResult(LZ4MT_RESULT_INVALID_HEADER);
			break;
		}

		if(sd->flg.streamSize) {
			sd->streamSize = loadU64(p);
			p += sizeof(uint64_t);
		}

		if(sd->flg.presetDictionary) {
			sd->dictId = loadU32(p);
			p += sizeof(uint32_t);
		}

		const auto sumSize   = static_cast<int>(p - sumBegin);
		const auto calHash32 = Lz4Mt::Xxh32(sumBegin, sumSize, LZ4S_CHECKSUM_SEED).digest();
		const auto calHash   = static_cast<char>(getCheckBits_FromXXH(calHash32));
		const auto srcHash   = *p++;

		assert(p <= std::end(d));

		if(srcHash != calHash) {
			ctx->setResult(LZ4MT_RESULT_INVALID_HEADER_CHECKSUM);
			break;
		}

		const auto nBlockMaximumSize = getBlockSize(sd->bd.blockMaximumSize);
		const auto nBlockCheckSum    = sd->flg.blockChecksum ? 4 : 0;
		const bool streamChecksum    = 0 != sd->flg.streamChecksum;
		const bool singleThread      = 0 != (ctx->mode() & LZ4MT_MODE_SEQUENTIAL);
		const auto nConcurrency      = Lz4Mt::getHardwareConcurrency();
		const auto nPool             = singleThread ? 1 : nConcurrency + 1;
		const auto launch            = singleThread ? Lz4Mt::launch::deferred : std::launch::async;

		Lz4Mt::MemPool srcBufferPool(nBlockMaximumSize, nPool);
		Lz4Mt::MemPool dstBufferPool(nBlockMaximumSize, nPool);
		std::vector<std::future<void>> futures;
		Lz4Mt::Xxh32 xxhStream(LZ4S_CHECKSUM_SEED);

		const auto f = [
			&futures, &dstBufferPool, &xxhStream, &quit
			, ctx, nBlockCheckSum, streamChecksum, launch
		] (int i, Lz4Mt::MemPool::Buffer* srcRaw, bool incompressible, uint32_t blockChecksum)
		{
			BufferPtr src(srcRaw);
			if(ctx->error() || quit) {
				return;
			}

			const auto* srcPtr = src->data();
			const auto srcSize = static_cast<int>(src->size());

			std::future<uint32_t> futureBlockHash;
			if(nBlockCheckSum) {
				futureBlockHash = std::async(launch, [=] {
					return Lz4Mt::Xxh32(srcPtr, srcSize, LZ4S_CHECKSUM_SEED).digest();
				});
			}

			if(incompressible) {
				if(i > 0) {
					futures[i-1].wait();
				}

				std::future<void> futureStreamHash;
				if(streamChecksum) {
					futureStreamHash = std::async(
						  launch
						, [&xxhStream, srcPtr, srcSize] {
							xxhStream.update(srcPtr, srcSize);
						}
					);
				}
				ctx->writeBin(srcPtr, srcSize);
				if(futureStreamHash.valid()) {
					futureStreamHash.wait();
				}
			} else {
				BufferPtr dst(dstBufferPool.alloc());

				auto* dstPtr = dst->data();
				const auto dstSize = dst->size();
				const auto decSize = ctx->decompress(
					srcPtr, dstPtr, srcSize, static_cast<int>(dstSize));
				if(decSize < 0) {
					quit = true;
					ctx->setResult(LZ4MT_RESULT_DECOMPRESS_FAIL);
					return;
				}

				if(i > 0) {
					futures[i-1].wait();
				}

				std::future<void> futureStreamHash;
				if(streamChecksum) {
					futureStreamHash = std::async(
						  launch
						, [&xxhStream, dstPtr, decSize] {
							xxhStream.update(dstPtr, decSize);
						}
					);
				}
				ctx->writeBin(dstPtr, decSize);
				if(futureStreamHash.valid()) {
					futureStreamHash.wait();
				}
			}

			if(futureBlockHash.valid()) {
				auto bh = futureBlockHash.get();
				if(bh != blockChecksum) {
					quit = true;
					ctx->setResult(LZ4MT_RESULT_BLOCK_CHECKSUM_MISMATCH);
					return;
				}
			}
			return;
		};

		for(int i = 0; !quit && !ctx->readEof(); ++i) {
			const auto srcBits = ctx->readU32();
			if(ctx->error()) {
				quit = true;
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_BLOCK_SIZE);
				break;
			}

			if(LZ4S_EOS == srcBits) {
				break;
			}

			const auto incompMask     = (1 << 31);
			const bool incompressible = 0 != (srcBits & incompMask);
			const auto srcSize        = static_cast<int>(srcBits & ~incompMask);

			BufferPtr src(srcBufferPool.alloc());
			const auto readSize = ctx->read(src->data(), srcSize);
			if(srcSize != readSize || ctx->error()) {
				quit = true;
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_BLOCK_DATA);
				break;
			}
			src->resize(readSize);

			const auto blockCheckSum = nBlockCheckSum ? ctx->readU32() : 0;
			if(ctx->error()) {
				quit = true;
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_BLOCK_CHECKSUM);
				break;
			}

			if(singleThread) {
				f(0, src.release(), incompressible, blockCheckSum);
			} else {
				futures.emplace_back(std::async(
					  launch
					, f, i, src.release(), incompressible, blockCheckSum
				));
			}
		}

		for(auto& e : futures) {
			e.wait();
		}

		if(!ctx->error() && streamChecksum) {
			const auto srcStreamChecksum = ctx->readU32();
			if(ctx->error()) {
				ctx->setResult(LZ4MT_RESULT_CANNOT_READ_STREAM_CHECKSUM);
				break;
			}
			if(xxhStream.digest() != srcStreamChecksum) {
				ctx->setResult(LZ4MT_RESULT_STREAM_CHECKSUM_MISMATCH);
				break;
			}
		}
	}

	return ctx->result();
}
Example #10
0
uint8_t execute_file (const char * fname){
    FRESULT res;
    FIL file;
    UINT readbytes;
    void (*dst)(void);

    /* XXX: why doesn't this work? sram_top contains garbage?
    dst=(void (*)(void)) (sram_top); 
    lcdPrint("T:"); lcdPrintIntHex(dst); lcdNl();
    */
    dst=(void (*)(void)) (0x10002000 - RAMCODE);

    res=f_open(&file, fname, FA_OPEN_EXISTING|FA_READ);

    //lcdPrint("open: ");
    //lcdPrintln(f_get_rc_string(res));
    //lcdRefresh();
    if(res){
        return -1;
    };
    
    res = f_read(&file, (char *)dst, RAMCODE, &readbytes);
    //lcdPrint("read: ");
    //lcdPrintln(f_get_rc_string(res));
    //lcdRefresh();
    if(res){
        return -1;
    };
#ifdef ENCRYPT_L0DABLE
    uint32_t *data;
    uint32_t len;
    uint32_t mac[4];
    data = (uint32_t*)dst;
    len = readbytes/4;

    if( readbytes & 0xF || readbytes <= 0x10){
        lcdClear();
        lcdPrint("!size");
        lcdRefresh();
        getInputWait();
        getInputWaitRelease();
        return -1;
    }

    xxtea_cbcmac(mac, (uint32_t*)dst, len-4, l0dable_sign_key);
    if( data[len-4] != mac[0] || data[len-3] != mac[1]
        || data[len-2] != mac[2] || data[len-1] != mac[3] ){
        lcdClear();
        lcdPrint("!mac");
        //lcdPrintIntHex(mac[0]); lcdNl();
        //lcdPrintIntHex(mac[1]); lcdNl();
        //lcdPrintIntHex(mac[2]); lcdNl();
        //lcdPrintIntHex(mac[3]); lcdNl();
        lcdRefresh();
        getInputWait();
        getInputWaitRelease();
        return -1;
    }
    data = (uint32_t*)dst;
    len = readbytes/4;
    xxtea_decode_words(data, len-4, l0dable_crypt_key);
#endif

    dst=(void (*)(void)) ((uint32_t)(dst) | 1); // Enable Thumb mode!
    dst();
    return 0;

};
void pix_opencv_patreco :: loadMess (t_symbol *s, int argc, t_atom* argv)
{
	t_symbol* filename;
	int id;
	
	if ( argc != 2 ) {
		error("wrong arguments : load <id> <filename>");
		return;
	} else if ( argv[0].a_type != A_FLOAT ||  argv[1].a_type != A_SYMBOL ) {
		error("wrong arguments : load <id> <filename>");
		return;
	} else {
		id = atom_getfloat(&argv[0]);
		filename = atom_getsymbol(&argv[1]);
	}
		
	
	if ( filename->s_name[0] == 0 ) {
		error("no filename passed to load message");
		return;
	}
	if ( filename == NULL ) { 
		error("%s is not a valid matrix", filename->s_name); 
		return;
	}
	
	Mat img = imread(filename->s_name,0);
	
	if ( img.data == NULL ){
		error("failed to load image '%s'", filename->s_name);
		puts("failed to laod images");
		return;
	}
	
	if(img.cols!=img.rows){
		error("%s is not a square pattern", filename->s_name);
		puts("not a square pattern");
		return;
	}

	cv::Mat src(m_pattern_size, m_pattern_size, CV_8UC1);
	Point2f center((m_pattern_size-1)/2.0f,(m_pattern_size-1)/2.0f);
	Mat rot_mat(2,3,CV_32F);
	
	//~ std::map<int PatternLib>::iterator it;
	//~ it = m_patternLibrary.find(id);
	//~ if ( m_patternLibrary.find(id) != m_patternLibrary.end() ){
		// TODO remove item from the map
	//~ }

	PatternLib pattern;
	pattern.id = id;
		
	cv::resize(img, src, Size(m_pattern_size,m_pattern_size));
	if ( m_detector->m_ART_pattern ) {
		Mat subImg = src(cv::Range(m_pattern_size/4,3*m_pattern_size/4), cv::Range(m_pattern_size/4,3*m_pattern_size/4));
		pattern.pattern[0]  = subImg;
		pattern.mean[0] = cvMean(&((CvMat)subImg));
		pattern.norm[0] = cv::norm(subImg, NORM_L1);
		//~ m_patternLibrary.push_back(subImg);
	}
	else {
		//~ m_patternLibrary.push_back(src);
		pattern.pattern[0]  = src;
		pattern.mean[0] = cvMean(&((CvMat)src));
		pattern.norm[0] = cv::norm(src, NORM_L1);
	}
	
	rot_mat = getRotationMatrix2D( center, 90, 1.0);

	for (int i=1; i<4; i++){
		Mat dst= Mat(m_pattern_size, m_pattern_size, CV_8UC1);
		rot_mat = getRotationMatrix2D( center, -i*90, 1.0);
		cv::warpAffine( src, dst , rot_mat, Size(m_pattern_size,m_pattern_size));
		if ( m_detector->m_ART_pattern ) {
			Mat subImg = dst(cv::Range(m_pattern_size/4,3*m_pattern_size/4), cv::Range(m_pattern_size/4,3*m_pattern_size/4)); // AV crop 25% on each side -> specific to AR tag ?
			pattern.pattern[i];
			pattern.mean[i] = cvMean(&((CvMat)subImg));
			pattern.norm[i] = cv::norm(subImg, NORM_L1);
			//~ m_patternLibrary.push_back(subImg);	
		} else {
			pattern.pattern[i] = dst;
			pattern.mean[i] = cvMean(&((CvMat)dst));
			pattern.norm[i] = cv::norm(dst, NORM_L1);			
			//~ m_patternLibrary.push_back(dst);
		}
	}

	t_atom data_out;
	SETFLOAT(&data_out, m_patternLibrary.size());
	outlet_anything( m_dataout, gensym("patternCount"), 1, &data_out);
}
Example #12
0
STDMETHODIMP CDX7SubPic::AlphaBlt(RECT* pSrc, RECT* pDst, SubPicDesc* pTarget)
{
    ASSERT(pTarget == nullptr);

    if (!m_pD3DDev || !m_pSurface || !pSrc || !pDst) {
        return E_POINTER;
    }

    CRect src(*pSrc), dst(*pDst);

    HRESULT hr;

    DDSURFACEDESC2 ddsd;
    INITDDSTRUCT(ddsd);
    if (FAILED(hr = m_pSurface->GetSurfaceDesc(&ddsd))) {
        return E_FAIL;
    }

    float w = (float)ddsd.dwWidth;
    float h = (float)ddsd.dwHeight;

    // Be careful with the code that follows. Some compilers (e.g. Visual Studio 2012) used to miscompile
    // it in some cases (namely x64 with optimizations /O2 /Ot). This bug led pVertices not to be correctly
    // initialized and thus the subtitles weren't shown.
    struct {
        float x, y, z, rhw;
        float tu, tv;
    } pVertices[] = {
        {(float)dst.left, (float)dst.top, 0.5f, 2.0f, (float)src.left / w, (float)src.top / h},
        {(float)dst.right, (float)dst.top, 0.5f, 2.0f, (float)src.right / w, (float)src.top / h},
        {(float)dst.left, (float)dst.bottom, 0.5f, 2.0f, (float)src.left / w, (float)src.bottom / h},
        {(float)dst.right, (float)dst.bottom, 0.5f, 2.0f, (float)src.right / w, (float)src.bottom / h},
    };

    for (size_t i = 0; i < _countof(pVertices); i++) {
        pVertices[i].x -= 0.5f;
        pVertices[i].y -= 0.5f;
    }

    hr = m_pD3DDev->SetTexture(0, m_pSurface);

    m_pD3DDev->SetRenderState(D3DRENDERSTATE_CULLMODE, D3DCULL_NONE);
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_LIGHTING, FALSE);
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_BLENDENABLE, TRUE);
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_SRCBLEND, D3DBLEND_ONE); // pre-multiplied src and ...
    m_pD3DDev->SetRenderState(D3DRENDERSTATE_DESTBLEND, m_bInvAlpha ? D3DBLEND_INVSRCALPHA : D3DBLEND_SRCALPHA); // ... inverse alpha channel for dst

    m_pD3DDev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
    m_pD3DDev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
    m_pD3DDev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);

    if (src == dst) {
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTFG_POINT);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTFG_POINT);
    } else {
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTFG_LINEAR);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTFG_LINEAR);
    }
    m_pD3DDev->SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTFP_NONE);

    m_pD3DDev->SetTextureStageState(0, D3DTSS_ADDRESS, D3DTADDRESS_CLAMP);

    /*//
    D3DDEVICEDESC7 d3ddevdesc;
    m_pD3DDev->GetCaps(&d3ddevdesc);
    if (d3ddevdesc.dpcTriCaps.dwAlphaCmpCaps & D3DPCMPCAPS_LESS)
    {
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAREF, (DWORD)0x000000FE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHATESTENABLE, TRUE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAFUNC, D3DPCMPCAPS_LESS);
    }
    *///

    if (FAILED(hr = m_pD3DDev->BeginScene())) {
        return E_FAIL;
    }

    hr = m_pD3DDev->DrawPrimitive(D3DPT_TRIANGLESTRIP,
                                  D3DFVF_XYZRHW | D3DFVF_TEX1,
                                  pVertices, 4, D3DDP_WAIT);
    m_pD3DDev->EndScene();

    m_pD3DDev->SetTexture(0, nullptr);

    return S_OK;
}
Example #13
0
//========================================================================
void AHexEditorActor::SaveMap(const FString& name)
{
	if (FPaths::FileExists(name))
	{
		//if file exists copy it to backup file to prevent overriding some maps
		auto newName = name;
		std::stringstream ss;	auto t = std::time(nullptr); ss << t;
		newName.Append(ss.str().c_str());
		std::ifstream src(*name, std::ios::binary);
		std::ofstream dst(*newName, std::ios::binary);
		dst << src.rdbuf();
		src.close();
		dst.close();
	}

	std::ofstream file;
	file.open(*name, std::ofstream::binary);
	
	auto& gridStorage = m_Grid.GetStorage();

	binary_write(file, (unsigned)gridStorage.size());
	this->Save(file); //editor tile first
	for (auto& pair : gridStorage)
	{
		if (pair.second != this)
		{
			pair.second->Save(file);
		}
	}

	binary_write(file, (unsigned)m_AllBarriers.size());
	for (auto* barrier : m_AllBarriers)
	{
		barrier->Save(file);
	}

	binary_write(file, (unsigned)m_AllPlatforms.size());
	for (auto* platform : m_AllPlatforms)
	{
		platform->Save(file);
	}

	binary_write(file, (unsigned)m_AllCompanions.size());
	for (auto* companion : m_AllCompanions)
	{
		companion->Save(file);
	}

	binary_write(file, (unsigned)m_AllBlockers.size());
	for (auto* blocker : m_AllBlockers)
	{
		blocker->Save(file);
	}

	binary_write(file, (unsigned)m_AllBridges.size());
	for (auto* bridges : m_AllBridges)
	{
		bridges->Save(file);
	}

	binary_write(file, (unsigned)m_AllTurrets.size());
	for (auto* turret : m_AllTurrets)
	{
		turret->Save(file);
	}

	binary_write(file, (unsigned)m_AllTeleports.size());
	for (auto* t : m_AllTeleports)
	{
		t->Save(file);
	}

	binary_write(file, m_Finish);
	m_Finish->Save(file);

	file.close();
}
//
// StencilTables factory
//
StencilTables const *
StencilTablesFactory::Create(TopologyRefiner const & refiner,
    Options options) {

    StencilTables * result = new StencilTables;

    int maxlevel = std::min(int(options.maxLevel), refiner.GetMaxLevel());
    if (maxlevel==0 and (not options.generateControlVerts)) {
        return result;
    }

    // 'maxsize' reflects the size of the default supporting basis factorized
    // in the stencils, with a little bit of head-room. Each subdivision scheme
    // has a set valence for 'regular' vertices, which drives the size of the
    // supporting basis of control-vertices. The goal is to reduce the number
    // of incidences where the pool allocator has to switch to dynamically
    // allocated heap memory when encountering extraordinary vertices that
    // require a larger supporting basis.
    //
    // The maxsize settings we use follow the assumption that the vast
    // majority of the vertices in a mesh are regular, and that the valence
    // of the extraordinary vertices is only higher by 1 edge.
    int maxsize = 0;
    bool interpolateVarying = false;
    switch (options.interpolationMode) {
        case INTERPOLATE_VERTEX: {
                Sdc::SchemeType type = refiner.GetSchemeType();
                switch (type) {
                    case Sdc::SCHEME_BILINEAR : maxsize = 5; break;
                    case Sdc::SCHEME_CATMARK  : maxsize = 17; break;
                    case Sdc::SCHEME_LOOP     : maxsize = 10; break;
                    default:
                        assert(0);
                }
            } break;
        case INTERPOLATE_VARYING: maxsize = 5; interpolateVarying=true; break;
        default:
            assert(0);
    }

    std::vector<StencilAllocator> allocators(
        options.generateIntermediateLevels ? maxlevel+1 : 2,
            StencilAllocator(maxsize, interpolateVarying));

    StencilAllocator * srcAlloc = &allocators[0],
                     * dstAlloc = &allocators[1];

    //
    // Interpolate stencils for each refinement level using
    // TopologyRefiner::InterpolateLevel<>()
    //
    for (int level=1;level<=maxlevel; ++level) {

        dstAlloc->Resize(refiner.GetNumVertices(level));

        if (options.interpolationMode==INTERPOLATE_VERTEX) {
            refiner.Interpolate(level, *srcAlloc, *dstAlloc);
        } else {
            refiner.InterpolateVarying(level, *srcAlloc, *dstAlloc);
        }

        if (options.generateIntermediateLevels) {
            if (level<maxlevel) {
                if (options.factorizeIntermediateLevels) {
                    srcAlloc = &allocators[level];
                } else {
                    // if the stencils are dependent on the previous level of
                    // subdivision, pass an empty allocator to treat all parent
                    // vertices as control vertices
                    assert(allocators[0].GetNumStencils()==0);
                }
                dstAlloc = &allocators[level+1];
            }
        } else {
            std::swap(srcAlloc, dstAlloc);
        }
    }

    // Copy stencils from the pool allocator into the tables
    {
        // Add total number of stencils, weights & indices
        int nelems = 0, nstencils=0;
        if (options.generateIntermediateLevels) {
            for (int level=0; level<=maxlevel; ++level) {
                nstencils += allocators[level].GetNumStencils();
                nelems += allocators[level].GetNumVerticesTotal();
            }
        } else {
            nstencils = (int)srcAlloc->GetNumStencils();
            nelems = srcAlloc->GetNumVerticesTotal();
        }

        // Allocate
        result->_numControlVertices = refiner.GetNumVertices(0);

        if (options.generateControlVerts) {
            nstencils += result->_numControlVertices;
            nelems += result->_numControlVertices;
        }
        result->resize(nstencils, nelems);

        // Copy stencils
        Stencil dst(&result->_sizes.at(0),
            &result->_indices.at(0), &result->_weights.at(0));

        if (options.generateControlVerts) {
            generateControlVertStencils(result->_numControlVertices, dst);
        }

        if (options.generateIntermediateLevels) {
            for (int level=1; level<=maxlevel; ++level) {
                for (int i=0; i<allocators[level].GetNumStencils(); ++i) {
                    *dst._size = allocators[level].CopyStencil(i, dst._indices, dst._weights);
                    dst.Next();
                }
            }
        } else {
            for (int i=0; i<srcAlloc->GetNumStencils(); ++i) {
                *dst._size = srcAlloc->CopyStencil(i, dst._indices, dst._weights);
                dst.Next();
            }
        }

        if (options.generateOffsets) {
            result->generateOffsets();
        }
    }

    return result;
}
TEST_F(RescalingTest, eightBitWindowSizeAssertion) {
    Image16bit src(5,6);
    Image8bit dst(4,5);
    int newMinPixelValue = 1;
    EXPECT_DEATH(Rescaling::clipTo8bits(src, dst, newMinPixelValue), "c*");
}
Example #16
0
STDMETHODIMP CDX7SubPic::AlphaBlt(RECT* pSrc, RECT* pDst, SubPicDesc* pTarget)
{
    ASSERT(pTarget == NULL);

    if (!m_pD3DDev || !m_pSurface || !pSrc || !pDst) {
        return E_POINTER;
    }

    CRect src(*pSrc), dst(*pDst);

    HRESULT hr;

    do {
        DDSURFACEDESC2 ddsd;
        INITDDSTRUCT(ddsd);
        if (FAILED(hr = m_pSurface->GetSurfaceDesc(&ddsd))) {
            break;
        }

        float w = (float)ddsd.dwWidth;
        float h = (float)ddsd.dwHeight;

        struct {
            float x, y, z, rhw;
            float tu, tv;
        }
        pVertices[] = {
            {(float)dst.left, (float)dst.top, 0.5f, 2.0f, (float)src.left / w, (float)src.top / h},
            {(float)dst.right, (float)dst.top, 0.5f, 2.0f, (float)src.right / w, (float)src.top / h},
            {(float)dst.left, (float)dst.bottom, 0.5f, 2.0f, (float)src.left / w, (float)src.bottom / h},
            {(float)dst.right, (float)dst.bottom, 0.5f, 2.0f, (float)src.right / w, (float)src.bottom / h},
        };
        /*
        for (ptrdiff_t i = 0; i < _countof(pVertices); i++)
        {
            pVertices[i].x -= 0.5;
            pVertices[i].y -= 0.5;
        }
        */
        hr = m_pD3DDev->SetTexture(0, m_pSurface);

        m_pD3DDev->SetRenderState(D3DRENDERSTATE_CULLMODE, D3DCULL_NONE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_LIGHTING, FALSE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_BLENDENABLE, TRUE);
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_SRCBLEND, D3DBLEND_ONE); // pre-multiplied src and ...
        m_pD3DDev->SetRenderState(D3DRENDERSTATE_DESTBLEND, D3DBLEND_SRCALPHA); // ... inverse alpha channel for dst

        m_pD3DDev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);

        m_pD3DDev->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTFG_LINEAR);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTFN_LINEAR);
        m_pD3DDev->SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTFP_LINEAR);

        m_pD3DDev->SetTextureStageState(0, D3DTSS_ADDRESS, D3DTADDRESS_CLAMP);

        /*//

        D3DDEVICEDESC7 d3ddevdesc;
        m_pD3DDev->GetCaps(&d3ddevdesc);
        if (d3ddevdesc.dpcTriCaps.dwAlphaCmpCaps & D3DPCMPCAPS_LESS)
        {
            m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAREF, (DWORD)0x000000FE);
            m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHATESTENABLE, TRUE);
            m_pD3DDev->SetRenderState(D3DRENDERSTATE_ALPHAFUNC, D3DPCMPCAPS_LESS);
        }

        *///

        if (FAILED(hr = m_pD3DDev->BeginScene())) {
            break;
        }

        hr = m_pD3DDev->DrawPrimitive(D3DPT_TRIANGLESTRIP,
                                      D3DFVF_XYZRHW | D3DFVF_TEX1,
                                      pVertices, 4, D3DDP_WAIT);
        m_pD3DDev->EndScene();

        //

        m_pD3DDev->SetTexture(0, NULL);

        return S_OK;
    } while (0);

    return E_FAIL;
}
Example #17
0
    void jacobi(
        crs_matrix<double> const & A
      , std::vector<double> const & b
      , std::size_t iterations
      , std::size_t block_size
    )
    {
        typedef std::vector<double> vector_type;

        std::shared_ptr<vector_type> dst(new vector_type(b));
        std::shared_ptr<vector_type> src(new vector_type(b));

        std::vector<range> block_ranges;
        // pre-computing ranges for the different blocks
        for(std::size_t i = 0; i < dst->size(); i += block_size)
        {
            block_ranges.push_back(
                range(i, std::min<std::size_t>(dst->size(), i + block_size)));
        }

        // pre-computing dependencies
        std::vector<std::vector<std::size_t> > dependencies(block_ranges.size());
        for(std::size_t b = 0; b < block_ranges.size(); ++b)
        {
            for(std::size_t i = block_ranges[b].begin(); i < block_ranges[b].end(); ++i)
            {
                std::size_t begin = A.row_begin(i);
                std::size_t end = A.row_end(i);

                for(std::size_t ii = begin; ii < end; ++ii)
                {
                    std::size_t idx = A.indices[ii];
                    for(std::size_t j = 0; j < block_ranges.size(); ++j)
                    {
                        if(block_ranges[j].begin() <= idx && idx < block_ranges[j].end())
                        {
                            if(std::find(dependencies[b].begin(),
                                dependencies[b].end(), j) == dependencies[b].end())
                            {
                                dependencies[b].push_back(j);
                            }
                            break;
                        }
                    }
                }
            }
        }

        typedef std::vector<hpx::shared_future<void> > future_vector;
        std::shared_ptr<future_vector> deps_dst
            (new future_vector(dependencies.size(), hpx::make_ready_future()));
        std::shared_ptr<future_vector> deps_src
            (new future_vector(dependencies.size(), hpx::make_ready_future()));

        hpx::util::high_resolution_timer t;
        for(std::size_t iter = 0; iter < iterations; ++iter)
        {
            for(std::size_t block = 0; block < block_ranges.size(); ++block)
            {
                std::vector<std::size_t> const & deps(dependencies[block]);
                std::vector<hpx::shared_future<void> > trigger;
                trigger.reserve(deps.size());
                for (std::size_t dep : deps)
                {
                    trigger.push_back((*deps_src)[dep]);
                }

                (*deps_dst)[block]
                    = hpx::when_all(std::move(trigger)).then(
                        hpx::launch::async,
                        hpx::util::bind(
                            jacobi_kernel_wrap
                          , block_ranges[block]
                          , std::cref(A)
                          , std::ref(*dst)
                          , std::cref(*src)
                          , std::cref(b)
                        )
                    );
            }
            std::swap(dst, src);
            std::swap(deps_dst, deps_src);
        }

        hpx::wait_all(*deps_dst);
        hpx::wait_all(*deps_src);

        double time_elapsed = t.elapsed();
        std::cout << dst->size() << " "
            << ((double(dst->size() * iterations)/1e6)/time_elapsed) << " MLUPS/s\n"
            << std::flush;
    }
Example #18
0
SkImage* SkImage::NewFromYUVTexturesCopy(GrContext* ctx , SkYUVColorSpace colorSpace,
                                         const GrBackendObject yuvTextureHandles[3],
                                         const SkISize yuvSizes[3],
                                         GrSurfaceOrigin origin) {
    const SkSurface::Budgeted budgeted = SkSurface::kYes_Budgeted;

    if (yuvSizes[0].fWidth <= 0 || yuvSizes[0].fHeight <= 0 ||
        yuvSizes[1].fWidth <= 0 || yuvSizes[1].fHeight <= 0 ||
        yuvSizes[2].fWidth <= 0 || yuvSizes[2].fHeight <= 0) {
        return nullptr;
    }
    static const GrPixelConfig kConfig = kAlpha_8_GrPixelConfig;
    GrBackendTextureDesc yDesc;
    yDesc.fConfig = kConfig;
    yDesc.fOrigin = origin;
    yDesc.fSampleCnt = 0;
    yDesc.fTextureHandle = yuvTextureHandles[0];
    yDesc.fWidth = yuvSizes[0].fWidth;
    yDesc.fHeight = yuvSizes[0].fHeight;

    GrBackendTextureDesc uDesc;
    uDesc.fConfig = kConfig;
    uDesc.fOrigin = origin;
    uDesc.fSampleCnt = 0;
    uDesc.fTextureHandle = yuvTextureHandles[1];
    uDesc.fWidth = yuvSizes[1].fWidth;
    uDesc.fHeight = yuvSizes[1].fHeight;

    GrBackendTextureDesc vDesc;
    vDesc.fConfig = kConfig;
    vDesc.fOrigin = origin;
    vDesc.fSampleCnt = 0;
    vDesc.fTextureHandle = yuvTextureHandles[2];
    vDesc.fWidth = yuvSizes[2].fWidth;
    vDesc.fHeight = yuvSizes[2].fHeight;

    SkAutoTUnref<GrTexture> yTex(ctx->textureProvider()->wrapBackendTexture(
        yDesc, kBorrow_GrWrapOwnership));
    SkAutoTUnref<GrTexture> uTex(ctx->textureProvider()->wrapBackendTexture(
        uDesc, kBorrow_GrWrapOwnership));
    SkAutoTUnref<GrTexture> vTex(ctx->textureProvider()->wrapBackendTexture(
        vDesc, kBorrow_GrWrapOwnership));
    if (!yTex || !uTex || !vTex) {
        return nullptr;
    }

    GrSurfaceDesc dstDesc;
    // Needs to be a render target in order to draw to it for the yuv->rgb conversion.
    dstDesc.fFlags = kRenderTarget_GrSurfaceFlag;
    dstDesc.fOrigin = origin;
    dstDesc.fWidth = yuvSizes[0].fWidth;
    dstDesc.fHeight = yuvSizes[0].fHeight;
    dstDesc.fConfig = kRGBA_8888_GrPixelConfig;
    dstDesc.fSampleCnt = 0;

    SkAutoTUnref<GrTexture> dst(ctx->textureProvider()->createTexture(dstDesc, true));
    if (!dst) {
        return nullptr;
    }

    GrPaint paint;
    paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode);
    paint.addColorFragmentProcessor(GrYUVtoRGBEffect::Create(yTex, uTex, vTex, yuvSizes,
                                                             colorSpace))->unref();

    const SkRect rect = SkRect::MakeWH(SkIntToScalar(dstDesc.fWidth),
                                       SkIntToScalar(dstDesc.fHeight));
    SkAutoTUnref<GrDrawContext> drawContext(ctx->drawContext(dst->asRenderTarget()));
    if (!drawContext) {
        return nullptr;
    }

    drawContext->drawRect(GrClip::WideOpen(), paint, SkMatrix::I(), rect);
    ctx->flushSurfaceWrites(dst);
    return new SkImage_Gpu(dstDesc.fWidth, dstDesc.fHeight, kNeedNewImageUniqueID,
                           kOpaque_SkAlphaType, dst, budgeted);
}
Example #19
0
	jobject get( JNIEnv* env, VARIANT* v, jclass retType ) {
		_variant_t dst(v);
		dst.ChangeType(VT_I4);
		
		return com4j_enumDictionary_get(env,retType,dst.intVal);
	}
Example #20
0
void crossCorr( const Mat& img, const Mat& _templ, Mat& corr,
                Size corrsize, int ctype,
                Point anchor, double delta, int borderType )
{
    const double blockScale = 4.5;
    const int minBlockSize = 256;
    std::vector<uchar> buf;

    Mat templ = _templ;
    int depth = img.depth(), cn = img.channels();
    int tdepth = templ.depth(), tcn = templ.channels();
    int cdepth = CV_MAT_DEPTH(ctype), ccn = CV_MAT_CN(ctype);

    CV_Assert( img.dims <= 2 && templ.dims <= 2 && corr.dims <= 2 );

    if( depth != tdepth && tdepth != std::max(CV_32F, depth) )
    {
        _templ.convertTo(templ, std::max(CV_32F, depth));
        tdepth = templ.depth();
    }

    CV_Assert( depth == tdepth || tdepth == CV_32F);
    CV_Assert( corrsize.height <= img.rows + templ.rows - 1 &&
               corrsize.width <= img.cols + templ.cols - 1 );

    CV_Assert( ccn == 1 || delta == 0 );

    corr.create(corrsize, ctype);

    int maxDepth = depth > CV_8S ? CV_64F : std::max(std::max(CV_32F, tdepth), cdepth);
    Size blocksize, dftsize;

    blocksize.width = cvRound(templ.cols*blockScale);
    blocksize.width = std::max( blocksize.width, minBlockSize - templ.cols + 1 );
    blocksize.width = std::min( blocksize.width, corr.cols );
    blocksize.height = cvRound(templ.rows*blockScale);
    blocksize.height = std::max( blocksize.height, minBlockSize - templ.rows + 1 );
    blocksize.height = std::min( blocksize.height, corr.rows );

    dftsize.width = std::max(getOptimalDFTSize(blocksize.width + templ.cols - 1), 2);
    dftsize.height = getOptimalDFTSize(blocksize.height + templ.rows - 1);
    if( dftsize.width <= 0 || dftsize.height <= 0 )
        CV_Error( CV_StsOutOfRange, "the input arrays are too big" );

    // recompute block size
    blocksize.width = dftsize.width - templ.cols + 1;
    blocksize.width = MIN( blocksize.width, corr.cols );
    blocksize.height = dftsize.height - templ.rows + 1;
    blocksize.height = MIN( blocksize.height, corr.rows );

    Mat dftTempl( dftsize.height*tcn, dftsize.width, maxDepth );
    Mat dftImg( dftsize, maxDepth );

    int i, k, bufSize = 0;
    if( tcn > 1 && tdepth != maxDepth )
        bufSize = templ.cols*templ.rows*CV_ELEM_SIZE(tdepth);

    if( cn > 1 && depth != maxDepth )
        bufSize = std::max( bufSize, (blocksize.width + templ.cols - 1)*
            (blocksize.height + templ.rows - 1)*CV_ELEM_SIZE(depth));

    if( (ccn > 1 || cn > 1) && cdepth != maxDepth )
        bufSize = std::max( bufSize, blocksize.width*blocksize.height*CV_ELEM_SIZE(cdepth));

    buf.resize(bufSize);

    // compute DFT of each template plane
    for( k = 0; k < tcn; k++ )
    {
        int yofs = k*dftsize.height;
        Mat src = templ;
        Mat dst(dftTempl, Rect(0, yofs, dftsize.width, dftsize.height));
        Mat dst1(dftTempl, Rect(0, yofs, templ.cols, templ.rows));

        if( tcn > 1 )
        {
            src = tdepth == maxDepth ? dst1 : Mat(templ.size(), tdepth, &buf[0]);
            int pairs[] = {k, 0};
            mixChannels(&templ, 1, &src, 1, pairs, 1);
        }

        if( dst1.data != src.data )
            src.convertTo(dst1, dst1.depth());

        if( dst.cols > templ.cols )
        {
            Mat part(dst, Range(0, templ.rows), Range(templ.cols, dst.cols));
            part = Scalar::all(0);
        }
        dft(dst, dst, 0, templ.rows);
    }

    int tileCountX = (corr.cols + blocksize.width - 1)/blocksize.width;
    int tileCountY = (corr.rows + blocksize.height - 1)/blocksize.height;
    int tileCount = tileCountX * tileCountY;

    Size wholeSize = img.size();
    Point roiofs(0,0);
    Mat img0 = img;

    if( !(borderType & BORDER_ISOLATED) )
    {
        img.locateROI(wholeSize, roiofs);
        img0.adjustROI(roiofs.y, wholeSize.height-img.rows-roiofs.y,
                       roiofs.x, wholeSize.width-img.cols-roiofs.x);
    }
    borderType |= BORDER_ISOLATED;

    // calculate correlation by blocks
    for( i = 0; i < tileCount; i++ )
    {
        int x = (i%tileCountX)*blocksize.width;
        int y = (i/tileCountX)*blocksize.height;

        Size bsz(std::min(blocksize.width, corr.cols - x),
                 std::min(blocksize.height, corr.rows - y));
        Size dsz(bsz.width + templ.cols - 1, bsz.height + templ.rows - 1);
        int x0 = x - anchor.x + roiofs.x, y0 = y - anchor.y + roiofs.y;
        int x1 = std::max(0, x0), y1 = std::max(0, y0);
        int x2 = std::min(img0.cols, x0 + dsz.width);
        int y2 = std::min(img0.rows, y0 + dsz.height);
        Mat src0(img0, Range(y1, y2), Range(x1, x2));
        Mat dst(dftImg, Rect(0, 0, dsz.width, dsz.height));
        Mat dst1(dftImg, Rect(x1-x0, y1-y0, x2-x1, y2-y1));
        Mat cdst(corr, Rect(x, y, bsz.width, bsz.height));

        for( k = 0; k < cn; k++ )
        {
            Mat src = src0;
            dftImg = Scalar::all(0);

            if( cn > 1 )
            {
                src = depth == maxDepth ? dst1 : Mat(y2-y1, x2-x1, depth, &buf[0]);
                int pairs[] = {k, 0};
                mixChannels(&src0, 1, &src, 1, pairs, 1);
            }

            if( dst1.data != src.data )
                src.convertTo(dst1, dst1.depth());

            if( x2 - x1 < dsz.width || y2 - y1 < dsz.height )
                copyMakeBorder(dst1, dst, y1-y0, dst.rows-dst1.rows-(y1-y0),
                               x1-x0, dst.cols-dst1.cols-(x1-x0), borderType);

            dft( dftImg, dftImg, 0, dsz.height );
            Mat dftTempl1(dftTempl, Rect(0, tcn > 1 ? k*dftsize.height : 0,
                                         dftsize.width, dftsize.height));
            mulSpectrums(dftImg, dftTempl1, dftImg, 0, true);
            dft( dftImg, dftImg, DFT_INVERSE + DFT_SCALE, bsz.height );

            src = dftImg(Rect(0, 0, bsz.width, bsz.height));

            if( ccn > 1 )
            {
                if( cdepth != maxDepth )
                {
                    Mat plane(bsz, cdepth, &buf[0]);
                    src.convertTo(plane, cdepth, 1, delta);
                    src = plane;
                }
                int pairs[] = {0, k};
                mixChannels(&src, 1, &cdst, 1, pairs, 1);
            }
            else
            {
                if( k == 0 )
                    src.convertTo(cdst, cdepth, 1, delta);
                else
                {
                    if( maxDepth != cdepth )
                    {
                        Mat plane(bsz, cdepth, &buf[0]);
                        src.convertTo(plane, cdepth);
                        src = plane;
                    }
                    add(src, cdst, cdst);
                }
            }
        }
    }
}
Example #21
0
	jobject get( JNIEnv* env, VARIANT* v, jclass retType ) {
		_variant_t dst(v);
		dst.ChangeType(vt);
		jobject o = XDUCER::toJava(env, addr(&dst));
		return o;
	}
Example #22
0
int main( int argc, char** argv ) {
    
    //! Number of cells in x direction
    int l_nX = 0;
    
    //! Number of cells in y direction
    int l_nY = 0;

	//! coarseness factor
	float l_coarseness = 1.0;
    
    //! l_baseName of the plots.
    std::string l_baseName;
    
    //! bathymetry input file name
    std::string l_bathymetryFileName;
    
    //! displacement input file name
    std::string l_displacementFileName;
    
    //! checkpoint input file name
    std::string l_checkpointFileName;
    
    //! the total simulation time
    int l_simulationTime = 0.0;

#ifdef USEOPENCL
    //! Maximum number of computing devices to be used (OpenCL specific, 0 = unlimited)
    unsigned int l_maxDevices = 0;
    
    //! Maximum kernel group size
    size_t l_maxGroupSize = 1024;
    
    //! Chosen kernel optimization type
    KernelType l_kernelType = MEM_GLOBAL;
#endif
    
    //! type of boundary conditions at LEFT, RIGHT, TOP, and BOTTOM boundary
    BoundaryType l_boundaryTypes[4];
    //! whether to override the scenario-defined conditions (true) or not (false)
    bool l_overwriteBoundaryTypes = false;
    
    //! List of defined scenarios
    typedef enum {
        SCENARIO_TSUNAMI, SCENARIO_CHECKPOINT_TSUNAMI,
        SCENARIO_ARTIFICIAL_TSUNAMI, SCENARIO_PARTIAL_DAMBREAK
    } ScenarioName;
    
    //! the name of the chosen scenario
    ScenarioName l_scenarioName;
#ifdef WRITENETCDF
    l_scenarioName = SCENARIO_TSUNAMI;
#else
    l_scenarioName = SCENARIO_PARTIAL_DAMBREAK;
#endif
    
    //! number of checkpoints for visualization (at each checkpoint in time, an output file is written).
    int l_numberOfCheckPoints = 20;
    
    // Option Parsing
    // REQUIRED
    // -x <num>        // Number of cells in x-dir
    // -y <num>        // Number of cells in y-dir
    // -o <file>       // Output file basename
    // OPTIONAL (may be required for certain scenarios)
    // -i <file>       // initial bathymetry data file name (REQUIRED for certain scenarios)
    // -d <file>       // input displacement data file name (REQUIRED for certain scenarios)
    // -c <file>       // checkpoints data file name
    // -f <float>      // output coarseness factor
    // -l <num>        // maximum number of computing devices
    // -m <code>       // Kernel memory optimization type
    // -g <num         // Kernel work group size
    // -n <num>        // Number of checkpoints
    // -t <float>      // Simulation time in seconds
    // -s <scenario>   // Artificial scenario name ("artificialtsunami", "partialdambreak")
    // -b <code>       // Boundary conditions, "w" or "o"
    //                 // 1 value: for all
    //                 // 2 values: first is left/right, second is top/bottom
    //                 // 4 values: left, right, bottom, top
    int c;
    int showUsage = 0;
    std::string optstr;
    while ((c = getopt(argc, argv, "x:y:o:i:d:c:n:t:b:s:f:l:m:g:")) != -1) {
        switch(c) {
            case 'x':
                l_nX = atoi(optarg);
                break;
            case 'y':
                l_nY = atoi(optarg);
                break;
            case 'o':
                l_baseName = std::string(optarg);
                break;
#ifdef WRITENETCDF
            case 'i':
                l_bathymetryFileName = std::string(optarg);
                break;
            case 'd':
                l_displacementFileName = std::string(optarg);
                break;
            case 'c':
                l_checkpointFileName = std::string(optarg);
                break;
#endif
            case 'l':
#ifdef USEOPENCL
                l_maxDevices = atoi(optarg);
#endif
                break;
            case 'g':
#ifdef USEOPENCL
                l_maxGroupSize = atoi(optarg);
#endif
            break;
            case 'm':
#ifdef USEOPENCL
                optstr = std::string(optarg);
                if(optstr == "g" || optstr == "global")
                    l_kernelType = MEM_GLOBAL;
                else
                    l_kernelType = MEM_LOCAL;
#endif
                break;
            case 'n':
                l_numberOfCheckPoints = atoi(optarg);
                break;
            case 't':
                l_simulationTime = atof(optarg);
                break;
            case 'b':
                optstr = std::string(optarg);
                l_overwriteBoundaryTypes = true;
                switch(optstr.length()) {
                    case 1:
                        // one option for all boundaries
                        for(int i = 0; i < 4; i++)
                            l_boundaryTypes[i] = (optstr[0] == 'w') ? WALL : OUTFLOW;
                        break;
                    case 2:
                        // first: left/right, second: top/bottom
                        for(int i = 0; i < 2; i++)
                            l_boundaryTypes[i] = (optstr[0] == 'w') ? WALL : OUTFLOW;
                        for(int i = 2; i < 4; i++)
                            l_boundaryTypes[i] = (optstr[1] == 'w') ? WALL : OUTFLOW;
                        break;
                    case 4:
                        // left right bottom top
                        for(int i = 0; i < 4; i++)
                            l_boundaryTypes[i] = (optstr[i] == 'w') ? WALL : OUTFLOW;
                        break;
                    default:
                        std::cerr << "Invalid option argument: Invalid boundary specification (-b)" << std::endl;
                        showUsage = 1;
                        break;
                }
                break;
            case 's':
                optstr = std::string(optarg);
                if(optstr == "artificialtsunami") {
                    l_scenarioName = SCENARIO_ARTIFICIAL_TSUNAMI;
                } else if(optstr == "partialdambreak") {
                    l_scenarioName = SCENARIO_PARTIAL_DAMBREAK;
                } else {
                    std::cerr << "Invalid option argument: Unknown scenario (-s)" << std::endl;
                    showUsage = 1;
                }
                break;
            case 'f':
                l_coarseness = atof(optarg);
                break;
            default:
                showUsage = 1;
                break;
        }
    }
    
    // Do several checks on supplied options
    if(!showUsage) {
        // Check for required arguments x and y cells unless we can get the info from a checkpoint file
        if((l_nX == 0 || l_nY == 0) && l_checkpointFileName.empty()) {
            std::cerr << "Missing required arguments: number of cells in X (-x) and Y (-y) direction" << std::endl;
            showUsage = 1;
        }
        // Check for required output base file name
        if(l_baseName.empty() && l_checkpointFileName.empty()) {
            std::cerr << "Missing required argument: base name of output file (-o)" << std::endl;
            showUsage = 1;
        }
        // Check for valid number of checkpoints
        if(l_numberOfCheckPoints <= 0) {
            std::cerr << "Invalid option argument: Number of checkpoints must be greater than zero (-n)" << std::endl;
            showUsage = 1;
        }
        
        if(l_coarseness < 1.0) {
            std::cerr << "Invalid option argument: The coarseness factor must be greater than or equal to 1.0 (-f)" << std::endl;
            showUsage = 1;
        }
        
        // Check if a checkpoint-file is given as input. If so, switch to checkpoint scenario
        if(!l_checkpointFileName.empty()) {
            l_scenarioName = SCENARIO_CHECKPOINT_TSUNAMI;
            
            // We handle the file name of checkpoint and output data files without the ".nc"
            // extension internally, so we're removing the extension here in case it is supplied
            int cpLength = l_checkpointFileName.length();
            if(l_checkpointFileName.substr(cpLength-3, 3).compare(".nc") == 0) {
                l_checkpointFileName.erase(cpLength-3, 3);
            }
            
            if(l_nX > 0 || l_nY > 0)
                std::cerr << "WARNING: Supplied number of grid cells will be ignored (reading from checkpoint)" << std::endl;
            if(l_simulationTime > 0.0)
                std::cerr << "WARNING: Supplied simulation time will be ignored (reading from checkpoint)" << std::endl;
        }
        
        if(l_scenarioName == SCENARIO_TSUNAMI) {
            // We've got no checkpoint and no artificial scenario
            // => Bathymetry and displacement data must be supplied
            if(l_bathymetryFileName.empty() || l_displacementFileName.empty()) {
                std::cerr << "Missing required argument: bathymetry (-i) and displacement (-d) files must be supplied" << std::endl;
                showUsage = 1;
            }
        } else {
            if(!l_bathymetryFileName.empty() || !l_displacementFileName.empty())
                std::cerr << "WARNING: Supplied bathymetry and displacement data will be ignored" << std::endl;
        }
#ifdef USEOPENCL
        if(l_maxGroupSize == 0 || (l_maxGroupSize & (l_maxGroupSize - 1))) {
            std::cout << "Group size must be greater than zero and a power of two!" << std::endl;
            showUsage = 1;
        }
#endif
    }
    
    if(showUsage) {
        std::cout << "Usage:" << std::endl;
        std::cout << "Simulating a tsunami with bathymetry and displacement input:" << std::endl;
        std::cout << "    ./SWE_<opt> -i <bathymetryfile> -d <displacementfile> [OPTIONS]" << std::endl;
        std::cout << "Resuming a crashed simulation from checkpoint file:" << std::endl;
        std::cout << "    ./SWE_<opt> -c <checkpointfile> [-o <outputfile>]" << std::endl;
        std::cout << "Simulating an artificial scenario:" << std::endl;
        std::cout << "    ./SWE_<opt> -s <scenarioname> [OPTIONS]" << std::endl;
        std::cout << "" << std::endl;
        std::cout << "Options:" << std::endl;
        std::cout << "    -o <filename>   The output file base name" << std::endl;
        std::cout << "        Note: If the file already exists it is assumed to be a checkpointfile" << std::endl;
        std::cout << "        from which to resume simulation. Input options are ignored then." << std::endl;
        std::cout << "    -x <num>        The number of cells in x-direction" << std::endl;
        std::cout << "    -y <num>        The number of cells in y-direction" << std::endl;
        std::cout << "    -n <num>        Number of checkpoints to be written" << std::endl;
        std::cout << "    -t <time>       Total simulation time" << std::endl;
        std::cout << "    -f <num>        Coarseness factor (> 1.0)" << std::endl;
        std::cout << "    -l <num>        Maximum number of computing devices (OpenCL only)" << std::endl;
        std::cout << "    -b <code>       Boundary Conditions" << std::endl;
        std::cout << "                    Codes: Combination of 'w' (WALL) and 'o' (OUTFLOW)" << std::endl;
        std::cout << "                      One char: Option for ALL boundaries" << std::endl;
        std::cout << "                      Two chars: Options for left/right and top/bottom boundaries" << std::endl;
        std::cout << "                      Four chars: Options for left, right, bottom, top boundaries" << std::endl;
        std::cout << "    -i <filename>   Name of bathymetry data file" << std::endl;
        std::cout << "    -d <filename>   Name of displacement data file" << std::endl;
        std::cout << "    -c <filename>   Name of checkpointfile" << std::endl;
        std::cout << "    -s <scenario>   Name of artificial scenario" << std::endl;
        std::cout << "                    Scenarios: 'artificialtsunami', 'partialdambreak'" << std::endl;
        std::cout << "" << std::endl;
        std::cout << "Notes when using a checkpointfile:" << std::endl;
        std::cout << "    -x, -y, -n, -t, -b, -i, -d, -s are ignored (values are read from checkpointfile)" << std::endl;
        std::cout << "    An output file (-o) can be specified. In that case, the checkpointfile" << std::endl;
        std::cout << "    is copied to that location and output is appended to the output file." << std::endl;
        std::cout << "    If no output file is specified, output is appended to the checkpointfile." << std::endl;
        std::cout << "" << std::endl;
        std::cout << "Example: " << std::endl; 
        std::cout << "./SWE_<compiler>_<build>_none_dimsplit -x 100 -y 200 -o out -i b.nc -d d.nc -n 50 -b owwo" << std::endl;
        std::cout << "    will simulate a tsunami scenario using bathymetry from 'b.nc' and displacements ";
        std::cout << "from 'd.nc' on a grid of size 100 x 200 using outflow conditions for left and ";
        std::cout << "top boundary and wall conditions for right and bottom boundary, writing 50 checkpoints ";
        std::cout << "to out_<num>.nc" << std::endl;
        
        return 0;
    }
    
    //! output file basename (with block coordinates)
    std::string l_outputFileName = generateBaseFileName(l_baseName,0,0);
    
#ifdef WRITENETCDF
    if(l_scenarioName != SCENARIO_CHECKPOINT_TSUNAMI) {
        // This is a tsunami scenario, check if the output file (with .nc-extension) exists
        // In that case switch to checkpoint scenario
        int ncOutputFile;
        int status = nc_open((l_outputFileName + ".nc").c_str(), NC_NOWRITE, &ncOutputFile);
        if(status == NC_NOERR) {
            // Output file exists and is a NetCDF file => switch to checkpointing
            l_scenarioName = SCENARIO_CHECKPOINT_TSUNAMI;
            l_checkpointFileName = l_outputFileName;
            nc_close(ncOutputFile);
        }
    }
#endif
    
    //! Pointer to instance of chosen scenario
    SWE_Scenario *l_scenario;
    
    // Create scenario according to chosen options
    switch(l_scenarioName) {
#ifdef WRITENETCDF
        case SCENARIO_TSUNAMI:
            l_scenario = new SWE_TsunamiScenario(l_bathymetryFileName, l_displacementFileName);
            
            // overwrite boundary conditions from scenario in case they have 
            // been explicitly set using command line arguments
            if(l_overwriteBoundaryTypes)
                ((SWE_TsunamiScenario *)l_scenario)->setBoundaryTypes(l_boundaryTypes);
            break;
        case SCENARIO_CHECKPOINT_TSUNAMI:
            l_scenario = new SWE_CheckpointTsunamiScenario(l_checkpointFileName + ".nc");
            
            // Read number if grid cells from checkpoint
            ((SWE_CheckpointTsunamiScenario *)l_scenario)->getNumberOfCells(l_nX, l_nY);
            
            if(l_overwriteBoundaryTypes)
                std::cerr << "WARNING: Loading checkpointed Simulation does not support "
                          << "explicitly setting boundary conditions" << std::endl;
            break;
#endif
        case SCENARIO_ARTIFICIAL_TSUNAMI:
            l_scenario = new SWE_ArtificialTsunamiScenario();

            // overwrite boundary conditions from scenario in case they have 
            // been explicitly set using command line arguments
            if(l_overwriteBoundaryTypes)
                ((SWE_ArtificialTsunamiScenario *)l_scenario)->setBoundaryTypes(l_boundaryTypes);
            break;
        case SCENARIO_PARTIAL_DAMBREAK:
            l_scenario = new SWE_PartialDambreak();
            if(l_overwriteBoundaryTypes)
                std::cerr << "WARNING: PartialDambreak-Scenario does not support "
                          << "explicitly setting boundary conditions" << std::endl;
            break;
        default:
            std::cerr << "Invalid Scenario" << std::endl;
            exit(1);
            break;
    }

    //! size of a single cell in x- and y-direction
    float l_dX, l_dY;
    
    // compute the size of a single cell
    l_dX = (l_scenario->getBoundaryPos(BND_RIGHT) - l_scenario->getBoundaryPos(BND_LEFT) )/l_nX;
    l_dY = (l_scenario->getBoundaryPos(BND_TOP) - l_scenario->getBoundaryPos(BND_BOTTOM) )/l_nY;
    
    //! Dimensional Splitting Block
#ifndef USEOPENCL
    SWE_DimensionalSplitting l_dimensionalSplitting(l_nX, l_nY, l_dX, l_dY);
#else
    SWE_DimensionalSplittingOpenCL l_dimensionalSplitting(l_nX, l_nY, l_dX, l_dY, 0, l_maxDevices, l_kernelType, l_maxGroupSize);
    l_dimensionalSplitting.printDeviceInformation();
#endif
    
    //! origin of the simulation domain in x- and y-direction
    float l_originX, l_originY;

    // get the origin from the scenario
    l_originX = l_scenario->getBoundaryPos(BND_LEFT);
    l_originY = l_scenario->getBoundaryPos(BND_BOTTOM);

    // initialize the wave propagation block
    l_dimensionalSplitting.initScenario(l_originX, l_originY, *l_scenario);
    
    //! time when the simulation ends.
    float l_endSimulation;
    if(l_simulationTime <= 0.0) {
        // We haven't got a valid simulation time as arguments, use the pre-defied one from scenario
        l_endSimulation = l_scenario->endSimulation();
    } else {
        // Use time given from command line
        l_endSimulation = l_simulationTime;
    }
    
    //! simulation time.
    float l_t = 0.0;
    
    //! checkpoint counter
    int l_checkpoint = 1;

#ifdef WRITENETCDF
    if(l_scenarioName == SCENARIO_CHECKPOINT_TSUNAMI) {
        // read total number of checkpoints
        l_numberOfCheckPoints = ((SWE_CheckpointTsunamiScenario *)l_scenario)->getNumberOfCheckpoints();
        
        // load last checkpoint and timestep from scenario (checkpoint-file)
        ((SWE_CheckpointTsunamiScenario *)l_scenario)->getLastCheckpoint(l_checkpoint, l_t);
        l_checkpoint++;
        
        // forace coarseness of 1 if reading from checkpoint data
        l_coarseness = 1.0;
    }
#endif
    
    // read actual boundary types (command line merged with scenario)
    l_boundaryTypes[BND_LEFT] = l_scenario->getBoundaryType(BND_LEFT);
    l_boundaryTypes[BND_RIGHT] = l_scenario->getBoundaryType(BND_RIGHT);
    l_boundaryTypes[BND_BOTTOM] = l_scenario->getBoundaryType(BND_BOTTOM);
    l_boundaryTypes[BND_TOP] = l_scenario->getBoundaryType(BND_TOP);
    
    //! checkpoints when output files are written.
    float* l_checkPoints = new float[l_numberOfCheckPoints+1];
    
    // compute the checkpoints in time
    for(int cp = 0; cp <= l_numberOfCheckPoints; cp++) {
        l_checkPoints[cp] = cp*(l_endSimulation/l_numberOfCheckPoints);
    }
    
    // Init fancy progressbar
    tools::ProgressBar progressBar(l_endSimulation);
    
    // write the output at time zero
    tools::Logger::logger.printOutputTime((float) l_t);
    progressBar.update(l_t);
    
    //boundary size of the ghost layers
    io::BoundarySize l_boundarySize = {{1, 1, 1, 1}};
    
    // Delete scenarioto free resources and close opened files
    delete l_scenario;
    
#ifdef WRITENETCDF
    if(l_scenarioName == SCENARIO_CHECKPOINT_TSUNAMI) {
        if(l_baseName.empty()) {
            // If there is no output file name given, use the checkpoint file
            l_outputFileName = l_checkpointFileName;
        } else if(l_outputFileName.compare(l_checkpointFileName) != 0) {
            // output file name given and it is not equal to the checkpoint file
            // therefore, we have to make a copy of our checkpointfile
            // in order to continue the simulation
            std::ifstream src((l_checkpointFileName + ".nc").c_str());
            std::ofstream dst((l_outputFileName + ".nc").c_str());
            dst << src.rdbuf();
        }
    }

    //construct a NetCdfWriter
    io::NetCdfWriter l_writer( l_outputFileName,
        l_dimensionalSplitting.getBathymetry(),
  		l_boundarySize,
  		l_nX, l_nY,
  		l_dX, l_dY,
  		l_originX, l_originY,
        l_coarseness);
        
        l_writer.writeSimulationInfo(l_numberOfCheckPoints, l_endSimulation, l_boundaryTypes);
#else
    // consturct a VtkWriter
    io::VtkWriter l_writer( l_outputFileName,
  		l_dimensionalSplitting.getBathymetry(),
  		l_boundarySize,
  		l_nX, l_nY,
  		l_dX, l_dY,
        0, 0,
        l_coarseness);
#endif
    if(l_scenarioName != SCENARIO_CHECKPOINT_TSUNAMI) {
        // Write zero time step
        l_writer.writeTimeStep( l_dimensionalSplitting.getWaterHeight(),
                                l_dimensionalSplitting.getDischarge_hu(),
                                l_dimensionalSplitting.getDischarge_hv(), 
                                (float) 0.);
    }
        
    /**
     * Simulation.
     */
    // print the start message and reset the wall clock time
    progressBar.clear();
    tools::Logger::logger.printStartMessage();
    tools::Logger::logger.initWallClockTime(time(NULL));
    
    progressBar.update(l_t);
    
    unsigned int l_iterations = 0;
    
    // loop over checkpoints
    while(l_checkpoint <= l_numberOfCheckPoints) {
        
        // do time steps until next checkpoint is reached
        while( l_t < l_checkPoints[l_checkpoint] ) {
            // set values in ghost cells:
            l_dimensionalSplitting.setGhostLayer();
            
            // reset the cpu clock
            tools::Logger::logger.resetCpuClockToCurrentTime();
            
            // compute numerical flux on each edge
            l_dimensionalSplitting.computeNumericalFluxes();
            
            //! maximum allowed time step width.
            float l_maxTimeStepWidth = l_dimensionalSplitting.getMaxTimestep();
            
            // update the cell values
            l_dimensionalSplitting.updateUnknowns(l_maxTimeStepWidth);
            
            // update the cpu time in the logger
            tools::Logger::logger.updateCpuTime();
            
            // update simulation time with time step width.
            l_t += l_maxTimeStepWidth;
            l_iterations++;
            
            // print the current simulation time
            progressBar.clear();
            tools::Logger::logger.printSimulationTime(l_t);
            progressBar.update(l_t);
        }
        // print current simulation time of the output
        progressBar.clear();
        tools::Logger::logger.printOutputTime(l_t);
        progressBar.update(l_t);
        
        // write output
        l_writer.writeTimeStep( l_dimensionalSplitting.getWaterHeight(),
                              l_dimensionalSplitting.getDischarge_hu(),
                              l_dimensionalSplitting.getDischarge_hv(),
                              l_t);
        
        l_checkpoint++;
    }
    
    /**
     * Finalize.
     */
    // write the statistics message
    progressBar.clear();
    tools::Logger::logger.printStatisticsMessage();
    
    // print the cpu time
    tools::Logger::logger.printCpuTime();
    
    // print the wall clock time (includes plotting)
    tools::Logger::logger.printWallClockTime(time(NULL));
    
    // printer iteration counter
    tools::Logger::logger.printIterationsDone(l_iterations);
    
    // print average time per cell per iteration
    tools::Logger::logger.printAverageCPUTimePerCellPerIteration(l_iterations, l_nX*(l_nY+2)); 
    
#ifdef USEOPENCL
    // print opencl stats
    l_dimensionalSplitting.printProfilingInformation();
#endif
    
    return 0;
}
Example #23
0
void SpriteBatchTest::render(float elapsedTime)
{
    // Clear the color and depth buffers
    clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0);

    Rectangle dst(0, 0, 64, 64);
    Rectangle src(0, 0, 256, 256);

    _spriteBatch->start();

    // Just a sprite dst from src no color tint
    _spriteBatch->draw(dst, src);

    // Color tint
    _spriteBatch->draw(Rectangle( 64, 0, 64, 64), src, Vector4::fromColor(0xF68B28FF));
    _spriteBatch->draw(Rectangle(128, 0, 64, 64), src, Vector4::fromColor(0xDA2128FF));
    _spriteBatch->draw(Rectangle(192, 0, 64, 64), src, Vector4::fromColor(0xE21B52FF));
    _spriteBatch->draw(Rectangle(256, 0, 64, 64), src, Vector4::fromColor(0xE12991FF));
    _spriteBatch->draw(Rectangle(320, 0, 64, 64), src, Vector4::fromColor(0x9A258FFF));
    _spriteBatch->draw(Rectangle(384, 0, 64, 64), src, Vector4::fromColor(0x4D3F99FF));
    _spriteBatch->draw(Rectangle(448, 0, 64, 64), src, Vector4::fromColor(0x0073BCFF));
    _spriteBatch->draw(Rectangle(512, 0, 64, 64), src, Vector4::fromColor(0x00A8DFFF));
    _spriteBatch->draw(Rectangle(576, 0, 64, 64), src, Vector4::fromColor(0x00AFADFF));
    _spriteBatch->draw(Rectangle(640, 0, 64, 64), src, Vector4::fromColor(0x00A95CFF));
    _spriteBatch->draw(Rectangle(704, 0, 64, 64), src, Vector4::fromColor(0x8CC747FF));
    _spriteBatch->draw(Rectangle(768, 0, 64, 64), src, Vector4::fromColor(0xFFE710FF));

    // Negative height draw over top of the first one
    _spriteBatch->draw(Rectangle(0, 0 , 64 * 2.0f, 64 * -2.0f), src);

    // Scale
    _spriteBatch->draw(Vector3(0, 64, 0), src, Vector2(dst.width * 2.0f, dst.height * 2.0f));
    // rotate 90
    _spriteBatch->draw(Vector3(128, 64, 0), src, Vector2(128, 128), Vector4(1, 1, 1, 1), Vector2(0.5f, 0.5f), MATH_DEG_TO_RAD(90));
    _spriteBatch->draw(Vector3(256, 64, 0), src, Vector2(128, 128), Vector4(1, 1, 1, 1), Vector2(0.5f, 0.5f), MATH_DEG_TO_RAD(180));
    _spriteBatch->draw(Vector3(384, 64, 0), src, Vector2(128, 128), Vector4(1, 1, 1, 1), Vector2(0.5f, 0.5f), MATH_DEG_TO_RAD(270));
    _spriteBatch->draw(Vector3(512, 64, 0), src, Vector2(128, 128), Vector4(1, 1, 1, 1), Vector2(0.5f, 0.5f), MATH_DEG_TO_RAD(360));
    _spriteBatch->draw(Vector3(640, 64, 0), src, Vector2(128, 128), Vector4(1, 1, 1, 1), Vector2(0.5f, 0.5f), MATH_DEG_TO_RAD(0));
    
    // Lots of them now small
    unsigned int pointCount = 16;
    unsigned int x = 0;
    unsigned int y = 192;
    for (unsigned int i = 0; i < pointCount; i++)
    {
        for (unsigned int j = 0; j < pointCount; j++)
        {
            _spriteBatch->draw(Rectangle(x, y, 32, 32), src); 
            x += 32;    
        }
        x = 0;
        y += 32;
    }
    _spriteBatch->finish();

    // Draw a second batch to ensure no problems
    _spriteBatch->start();

    // 50% transparent
    _spriteBatch->draw(Rectangle(x + 512, y - 512, 512, 512), src, Vector4(1, 1, 1, 0.5f)); 
    _spriteBatch->finish();

    drawFrameRate(_font, Vector4(0, 0.5f, 1, 1), 5, 1, getFrameRate());
}
Example #24
0
//=======================================================================
//function : GetMinDistanceSingular
//purpose  : 
//=======================================================================
double GEOMUtils::GetMinDistanceSingular(const TopoDS_Shape& aSh1,
                                         const TopoDS_Shape& aSh2,
                                         gp_Pnt& Ptmp1, gp_Pnt& Ptmp2)
{
  TopoDS_Shape     tmpSh1;
  TopoDS_Shape     tmpSh2;
  Standard_Real    AddDist1 = 0.;
  Standard_Real    AddDist2 = 0.;
  Standard_Boolean IsChange1 = ModifyShape(aSh1, tmpSh1, AddDist1);
  Standard_Boolean IsChange2 = ModifyShape(aSh2, tmpSh2, AddDist2);

  if( !IsChange1 && !IsChange2 )
    return -2.0;

  BRepExtrema_DistShapeShape dst(tmpSh1,tmpSh2);
  if (dst.IsDone()) {
    double MinDist = 1.e9;
    gp_Pnt PMin1, PMin2, P1, P2;
    for (int i = 1; i <= dst.NbSolution(); i++) {
      P1 = dst.PointOnShape1(i);
      P2 = dst.PointOnShape2(i);
      Standard_Real Dist = P1.Distance(P2);
      if (MinDist > Dist) {
        MinDist = Dist;
        PMin1 = P1;
        PMin2 = P2;
      }
    }
    if(MinDist<1.e-7) {
      Ptmp1 = PMin1;
      Ptmp2 = PMin2;
    }
    else {
      gp_Dir aDir(gp_Vec(PMin1,PMin2));
      if( MinDist > (AddDist1+AddDist2) ) {
        Ptmp1 = gp_Pnt( PMin1.X() + aDir.X()*AddDist1,
                        PMin1.Y() + aDir.Y()*AddDist1,
                        PMin1.Z() + aDir.Z()*AddDist1 );
        Ptmp2 = gp_Pnt( PMin2.X() - aDir.X()*AddDist2,
                        PMin2.Y() - aDir.Y()*AddDist2,
                        PMin2.Z() - aDir.Z()*AddDist2 );
        return (MinDist - AddDist1 - AddDist2);
      }
      else {
        if( AddDist1 > 0 ) {
          Ptmp1 = gp_Pnt( PMin1.X() + aDir.X()*AddDist1,
                          PMin1.Y() + aDir.Y()*AddDist1,
                          PMin1.Z() + aDir.Z()*AddDist1 );
          Ptmp2 = Ptmp1;
        }
        else {
          Ptmp2 = gp_Pnt( PMin2.X() - aDir.X()*AddDist2,
                          PMin2.Y() - aDir.Y()*AddDist2,
                          PMin2.Z() - aDir.Z()*AddDist2 );
          Ptmp1 = Ptmp2;
        }
      }
    }
    double res = MinDist - AddDist1 - AddDist2;
    if(res<0.) res = 0.0;
    return res;
  }
  return -2.0;
}
Example #25
0
MetaImage::Handle MetaImage::create(Image::Handle i, 
                                    ImageDisplaySetting::Handle d)
{
  Handle dst(new MetaImage(i,d));
  return dst;
}  
Example #26
0
Pixmap GLXConfigurator::CreateBackdrop(Window rootWindow, int depth) {
    int bpl;
    /* Find out number of bytes per pixel */
    switch(depth) {
    default:
        LogManager::getSingleton().logMessage("GLX backdrop: Unsupported bit depth");
        /* Unsupported bit depth */
        return 0;
    case 15:
    case 16:
        bpl = 2; break;
    case 24:
    case 32:
        bpl = 4; break;
    }
    /* Create background pixmap */
    unsigned char *data = 0; // Must be allocated with malloc

    try {
        String imgType = "png";
        Image img;
        MemoryDataStream *imgStream;
        DataStreamPtr imgStreamPtr;

        // Load backdrop image using OGRE
        imgStream = new MemoryDataStream(const_cast<unsigned char*>(GLX_backdrop_data), sizeof(GLX_backdrop_data), false);
        imgStreamPtr = DataStreamPtr(imgStream);
        img.load(imgStreamPtr, imgType);

        PixelBox src = img.getPixelBox(0, 0);

        // Convert and copy image
        data = (unsigned char*)malloc(mWidth * mHeight * bpl); // Must be allocated with malloc

        PixelBox dst(src, bpl == 2 ? PF_B5G6R5 : PF_A8R8G8B8, data );

        PixelUtil::bulkPixelConversion(src, dst);
    } catch(Exception &e) {
        // Could not find image; never mind
        LogManager::getSingleton().logMessage("WARNING: Can not load backdrop for config dialog. " + e.getDescription(), LML_TRIVIAL);
        return 0;
    }

    GC context = XCreateGC (mDisplay, rootWindow, 0, NULL);

    /* put my pixmap data into the client side X image data structure */
    XImage *image = XCreateImage (mDisplay, NULL, depth, ZPixmap, 0,
        (char*)data,
        mWidth, mHeight, 8,
        mWidth*bpl);
#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
    image->byte_order = MSBFirst;
#else
    image->byte_order = LSBFirst;
#endif

    /* tell server to start managing my pixmap */
    Pixmap rv = XCreatePixmap(mDisplay, rootWindow, mWidth,
        mHeight, depth);

    /* copy from client to server */
    XPutImage(mDisplay, rv, context, image, 0, 0, 0, 0,
        mWidth, mHeight);

    /* free up the client side pixmap data area */
    XDestroyImage(image); // also cleans data
    XFreeGC(mDisplay, context);

    return rv;
}
Example #27
0
// Commit
//------------------------------------------------------------------------------
/*virtual*/ bool FunctionCopy::Commit( NodeGraph & nodeGraph, const BFFIterator & funcStartIter ) const
{
    // make sure all required variables are defined
    Array< AString > sources( 16, true );
    const BFFVariable * dstFileV;
    if ( !GetStrings( funcStartIter, sources, ".Source", true ) ||
         !GetString( funcStartIter, dstFileV, ".Dest", true ) )
    {
        return false; // GetString will have emitted errors
    }

    // Optional
    AStackString<> sourceBasePath;
    if ( !GetString( funcStartIter, sourceBasePath, ".SourceBasePath", false ) )
    {
        return false; // GetString will have emitted errors
    }

    // Canonicalize the SourceBasePath
    if ( !sourceBasePath.IsEmpty() )
    {
        AStackString<> cleanValue;
        NodeGraph::CleanPath( sourceBasePath, cleanValue );
        PathUtils::EnsureTrailingSlash( cleanValue );
        sourceBasePath = cleanValue;
    }

    // check sources are not paths
    {
        const AString * const end = sources.End();
        for ( const AString * it = sources.Begin(); it != end; ++it )
        {
            const AString & srcFile( *it );

            // source must be a file, not a  path
            if ( PathUtils::IsFolderPath( srcFile ) )
            {
                Error::Error_1105_PathNotAllowed( funcStartIter, this, ".Source", srcFile );
                return false;
            }
        }
    }

    // Pre-build dependencies
    Dependencies preBuildDependencies;
    if ( !GetNodeList( nodeGraph, funcStartIter, ".PreBuildDependencies", preBuildDependencies, false ) )
    {
        return false; // GetNodeList will have emitted an error
    }
    Array< AString > preBuildDependencyNames( preBuildDependencies.GetSize(), false );
    for ( const auto & dep : preBuildDependencies )
    {
        preBuildDependencyNames.Append( dep.GetNode()->GetName() );
    }

    // get source node
    Array< Node * > srcNodes;
    {
        const AString * const end = sources.End();
        for ( const AString * it = sources.Begin(); it != end; ++it )
        {

            Node * srcNode = nodeGraph.FindNode( *it );
            if ( srcNode )
            {
                if ( GetSourceNodes( funcStartIter, srcNode, srcNodes ) == false )
                {
                    return false;
                }
            }
            else
            {
                // source file not defined by use - assume an external file
                srcNodes.Append( nodeGraph.CreateFileNode( *it ) );
            }
        }
    }

    AStackString<> dstFile;
    NodeGraph::CleanPath( dstFileV->GetString(), dstFile );
    const bool dstIsFolderPath = PathUtils::IsFolderPath( dstFile );

    // make all the nodes for copies
    Dependencies copyNodes( srcNodes.GetSize(), false );
    for ( const Node * srcNode : srcNodes )
    {
        AStackString<> dst( dstFile );

        // dest can be a file OR a path.  If it's a path, use the source filename part
        if ( dstIsFolderPath )
        {
            // find filename part of source
            const AString & srcName = srcNode->GetName();

            // If the sourceBasePath is specified (and valid) use the name relative to that
            if ( !sourceBasePath.IsEmpty() && PathUtils::PathBeginsWith( srcName, sourceBasePath ) )
            {
                // Use everything relative to the SourceBasePath
                dst += srcName.Get() + sourceBasePath.GetLength();
            }
            else
            {
                // Use just the file name
                const char * lastSlash = srcName.FindLast( NATIVE_SLASH );
                dst += lastSlash ? ( lastSlash + 1 )    // append filename part if found
                                     : srcName.Get();   // otherwise append whole thing
            }
        }

        // check node doesn't already exist
        if ( nodeGraph.FindNode( dst ) )
        {
            // TODO:C could have a specific error for multiple sources with only 1 output
            // to differentiate from two rules creating the same dst target
            Error::Error_1100_AlreadyDefined( funcStartIter, this, dst );
            return false;
        }

        // create our node
        CopyFileNode * copyFileNode = nodeGraph.CreateCopyFileNode( dst );
        copyFileNode->m_Source = srcNode->GetName();
        copyFileNode->m_PreBuildDependencyNames = preBuildDependencyNames;
        if ( !copyFileNode->Initialize( nodeGraph, funcStartIter, this ) )
        {
            return false; // Initialize will have emitted an error
        }

        copyNodes.Append( Dependency( copyFileNode ) );
    }

    // handle alias creation
    return ProcessAlias( nodeGraph, funcStartIter, copyNodes );
}
SimpleTensor<T> non_linear_filter(const SimpleTensor<T> &src, NonLinearFilterFunction function, unsigned int mask_size, MatrixPattern pattern, const uint8_t *mask, BorderMode border_mode,
                                  uint8_t constant_border_value)
{
    SimpleTensor<T> dst(src.shape(), src.data_type());

    ARM_COMPUTE_ERROR_ON(pattern == MatrixPattern::OTHER && mask == nullptr);
    ARM_COMPUTE_UNUSED(pattern);

    using intermediate_type = typename common_promoted_signed_type<T>::intermediate_type;

    const int                      sq_mask_size   = mask_size * mask_size;
    const int                      half_mask_size = mask_size / 2;
    std::vector<intermediate_type> vals(sq_mask_size);
    intermediate_type              current_value = 0;

    const ValidRegion valid_region = shape_to_valid_region(src.shape(), border_mode == BorderMode::UNDEFINED, BorderSize(half_mask_size));

    for(int element_idx = 0, count = 0, index = 0; element_idx < src.num_elements(); ++element_idx, count = 0, index = 0)
    {
        Coordinates id = index2coord(src.shape(), element_idx);
        if(is_in_valid_region(valid_region, id))
        {
            int idx = id.x();
            int idy = id.y();
            for(int y = idy - half_mask_size; y <= idy + half_mask_size; ++y)
            {
                for(int x = idx - half_mask_size; x <= idx + half_mask_size; ++x, ++index)
                {
                    id.set(0, x);
                    id.set(1, y);
                    current_value = tensor_elem_at(src, id, border_mode, constant_border_value);

                    if(mask[index] == 255)
                    {
                        vals[count] = static_cast<intermediate_type>(current_value);
                        ++count;
                    }
                }
            }
            std::sort(vals.begin(), vals.begin() + count);

            ARM_COMPUTE_ERROR_ON(count == 0);

            switch(function)
            {
                case NonLinearFilterFunction::MIN:
                    dst[element_idx] = saturate_cast<T>(vals[0]);
                    break;
                case NonLinearFilterFunction::MAX:
                    dst[element_idx] = saturate_cast<T>(vals[count - 1]);
                    break;
                case NonLinearFilterFunction::MEDIAN:
                    dst[element_idx] = saturate_cast<T>(vals[count / 2]);
                    break;
                default:
                    ARM_COMPUTE_ERROR("Unsupported NonLinearFilter function.");
            }
        }
    }

    return dst;
}
Example #29
0
uint8_t execute_file (const char * fname){
    FRESULT res;
    FIL file;
    UINT readbytes;
    void (*dst)(void);
    uint32_t version=0;

    res=f_open(&file, fname, FA_OPEN_EXISTING|FA_READ);
    if (res!=FR_OK){
	lcdPrintln(f_get_rc_string(res));
	lcdDisplay();
	return -1;
    };

    res = f_read(&file, &version, sizeof(uint32_t), &readbytes);
    if(res!=FR_OK){
	lcdPrintln(f_get_rc_string(res));
	lcdDisplay();
        return -1;
    };

    if (version>jumptable_len){
	lcdPrintln("l0dable incompat.");
	lcdPrint(IntToStr(jumptable_len,4,F_HEX));
	lcdPrint(" < ");
	lcdPrintln(IntToStr(version,4,F_HEX));
	lcdDisplay();
        return -1;
    };

    res = f_read(&file, &dst, sizeof(uint32_t), &readbytes);
    if(res!=FR_OK){
	lcdPrintln(f_get_rc_string(res));
	lcdDisplay();
        return -1;
    };

    if ((uintptr_t)dst<l0dable_start || (uintptr_t)dst>(l0dable_start+l0dable_len)){
	lcdPrintln("l0daddr illegal");
	lcdPrint(IntToStr((uintptr_t)dst,8,F_HEX));
	lcdDisplay();
        return -1;
    };


    res = f_read(&file, (uint8_t *)l0dable_start, l0dable_len, &readbytes);
    if(res!=FR_OK){
	lcdPrintln(f_get_rc_string(res));
	lcdDisplay();
        return -1;
    };

    if(readbytes>=l0dable_len){
	lcdPrintln("l0dable too long.");
	lcdDisplay();
	return -1;
    };

    lcdPrint(IntToStr(readbytes,5,F_LONG));
    lcdPrintln(" bytes...");

    dst=(void (*)(void)) ((uintptr_t)dst|1); // Enable Thumb mode!

#if 0
    lcdPrint("dst= "); lcdPrint(IntToStr((uintptr_t)dst,8,F_HEX)); lcdNl();
    lcdPrint("len= "); lcdPrint(IntToStr((uintptr_t)&_l0dable_len,8,F_HEX)); lcdNl();
    lcdPrint("jt=  "); lcdPrint(IntToStr(jumptable_len,8,F_HEX)); lcdNl();
    lcdPrint("ver= "); lcdPrint(IntToStr(version,8,F_HEX)); lcdNl();
    lcdDisplay();
#endif

    dst();
    return 0;
}
Example #30
0
wxRect FenetreZoom::CalculPosRectDst(wxRect &src,wxPoint *p)
{
    wxRect	recSrc(0,0,fMere->ImAcq()->cols,fMere->ImAcq()->rows);
    wxRect	rMax;
    long	origX=0,origY=0;
    int		fZoomNume,fZoomDeno;
    wxPoint	refPos(0,0);

    if (p)
        refPos= *p;


    CalculZoom(fZoomNume,fZoomDeno);

    rMax=this->GetClientRect();
    wxPoint	p1(0,0);
    wxPoint	p2(	(rMax.GetRight()+fZoomNume-1)/fZoomDeno*fZoomDeno,
                (rMax.GetBottom()+fZoomNume-1)/fZoomDeno*fZoomDeno);

    wxPoint	p1Img=RepereEcranImage(p1);
    wxPoint	p2Img=RepereEcranImage(p2);
    wxPoint	transLat(refPos.x-p2Img.x/2,refPos.y-p2Img.y/2);
    p2Img.x += fZoomDeno-1;
    p2Img.y += fZoomDeno-1;
    if (p)
    {
        p1Img += transLat;
        p2Img += transLat;
    }

    if (!recSrc.Contains(p1Img))
    {
        if (p1Img.x<0)
        {
            p2Img.x+= -p1Img.x;
            p1Img.x =0;
        }
        if (p1Img.y<0)
        {
            p2Img.y+= -p1Img.y;
            p1Img.y =0;
        }
    }
    if (!recSrc.Contains(p2Img))
    {
        if (p2Img.x>=recSrc.GetRight())
        {
            p1Img.x += recSrc.GetRight()-p2Img.x-1;
            p2Img.x = recSrc.GetRight()-1;
        }
        if (p2Img.y>=recSrc.GetBottom())
        {
            p1Img.y += recSrc.GetBottom()-p2Img.y-1;
            p2Img.y = recSrc.GetBottom()-1;
        }

    }
    p2 = RepereImageEcran(p2Img);
    p1 = RepereImageEcran(p1Img);
    wxRect dst(p1,p2);
    src=wxRect(p1Img,p2Img);
    return dst;
    long largeur = p2Img.x - p1Img.x;
    long hauteur = p2Img.y - p1Img.y;
    origX = p->x-largeur/2;
    long right = p->x+largeur/2;
    origY = p->y-hauteur/2;
    long bottom = p->y+hauteur/2;
    if (recSrc.GetRight()<right)
    {
        right= recSrc.GetRight();
        origX = right-largeur;
    }
    if (recSrc.GetBottom()<bottom)
    {
        bottom= recSrc.GetBottom();
        origY = bottom-hauteur;
    }
    if (recSrc.GetLeft()>origX)
    {
        origX= recSrc.GetLeft();
        right = origX+largeur;
    }
    if (recSrc.GetTop()>origY)
    {
        origY= recSrc.GetTop();
        bottom = origY +hauteur;
    }
    src=wxRect(origX,origY,right,bottom);
    return dst;
}