Esempio n. 1
0
void TTile::addInCache(const TRasterP &raster) {
  if (!raster) {
    m_rasterId = "";
    return;
  }
  TRasterP rin;

  m_rasterId = TImageCache::instance()->getUniqueId();
  if (raster->getParent()) {
    rin = raster->getParent();
    unsigned long offs =
        (raster->getRawData() - raster->getParent()->getRawData()) /
        raster->getPixelSize();
    m_subRect =
        TRect(TPoint(offs % raster->getWrap(), offs / raster->getWrap()),
              raster->getSize());
  } else {
    m_subRect = raster->getBounds();
    rin       = raster;
  }

  if ((TRasterCM32P)rin)
    TImageCache::instance()->add(m_rasterId,
                                 TToonzImageP(rin, rin->getBounds()));
  else if ((TRaster32P)rin || (TRaster64P)rin)
    TImageCache::instance()->add(m_rasterId, TRasterImageP(rin));
  else if ((TRasterGR8P)rin || (TRasterGR16P)rin)
    TImageCache::instance()->add(m_rasterId, TRasterImageP(rin));
  else
    assert(false);
}
Esempio n. 2
0
inline TRasterP TCacheResource::createCellRaster(int rasterType, const std::string &cacheId)
{
	TRasterP result;

	if (rasterType == TCacheResource::NONE) {
		assert(!"Unknown raster type!");
		return result;
	}

	TImageP img;
	if (rasterType == TCacheResource::RGBM32) {
		result = TRaster32P(latticeStep, latticeStep);
		img = TRasterImageP(result);
	} else if (rasterType == TCacheResource::RGBM64) {
		result = TRaster64P(latticeStep, latticeStep);
		img = TRasterImageP(result);
	} else if (rasterType == TCacheResource::CM32) {
		result = TRasterCM32P(latticeStep, latticeStep);
		img = TToonzImageP(result, result->getBounds());
	}

	TImageCache::instance()->add(cacheId, img);
	++m_cellsCount;

	//DIAGNOSTICS_GLOADD("crCellsCnt", 1);

	return result;
}
Esempio n. 3
0
TRasterImageP Ffmpeg::getImage(int frameIndex) {
  QString ffmpegCachePath = getFfmpegCache().getQString();
  QString tempPath        = ffmpegCachePath + "//" + cleanPathSymbols();
  std::string tmpPath     = tempPath.toStdString();
  // QString tempPath= m_path.getQString();
  QString number   = QString("%1").arg(frameIndex, 4, 10, QChar('0'));
  QString tempName = "In" + number + ".png";
  tempName         = tempPath + tempName;

  // for debugging
  std::string strPath = tempName.toStdString();
  if (TSystem::doesExistFileOrLevel(TFilePath(tempName))) {
    QImage *temp = new QImage(tempName, "PNG");
    if (temp) {
      QImage tempToo = temp->convertToFormat(QImage::Format_ARGB32);
      delete temp;
      const UCHAR *bits = tempToo.bits();

      TRasterPT<TPixelRGBM32> ret;
      ret.create(m_lx, m_ly);
      ret->lock();
      memcpy(ret->getRawData(), bits, m_lx * m_ly * 4);
      ret->unlock();
      ret->yMirror();
      return TRasterImageP(ret);
    }
  } else
    return TRasterImageP();
}
Esempio n. 4
0
std::pair<TRasterP, TCacheResource::CellData *> TCacheResource::touch(const PointLess &cellIndex)
{
	std::string cellId(getCellCacheId(cellIndex.x, cellIndex.y));

	std::map<PointLess, CellData>::iterator it = m_cellDatas.find(cellIndex);
	if (it != m_cellDatas.end()) {
		//Retrieve the raster from image cache
		TImageP img(TImageCache::instance()->get(cellId, true));
		if (img)
			return std::make_pair(getRaster(img), &it->second);
	}

	it = m_cellDatas.insert(std::make_pair(cellIndex, CellData())).first;

	//Then, attempt retrieval from back resource
	TRasterP ras(load(cellIndex));
	if (ras) {
		TImageCache::instance()->add(cellId, TRasterImageP(ras));
		return std::make_pair(ras, &it->second);
	}

	//Else, create it
	return std::make_pair(
		createCellRaster(m_tileType, cellId), //increases m_cellsCount too
		&it->second);
}
Esempio n. 5
0
TImageP TImageReader3gp::load()
{
	TRasterPT<TPixelRGBM32> ret(m_lrm->getSize());

	m_lrm->load(ret, m_frameIndex, TPointI(), 1, 1);

	return TRasterImageP(ret);
}
Esempio n. 6
0
TImageP ImageFiller::build(int imFlags, void *extData)
{
	assert(imFlags == ImageManager::none);

	// Fetch image
	assert(extData);

	ImageLoader::BuildExtData *data = (ImageLoader::BuildExtData *)extData;
	assert(data->m_subs == 0);

	const std::string &srcImgId = data->m_sl->getImageId(data->m_fid);

	TImageP img = ImageManager::instance()->getImage(srcImgId, imFlags, extData);
	if (img) {
		TRasterImageP ri = img;
		if (ri) {
			TRaster32P ras = ri->getRaster();
			if (ras) {
				TRaster32P newRas = ras->clone();
				FullColorAreaFiller filler(newRas);

				TPaletteP palette = new TPalette();
				int styleId = palette->getPage(0)->addStyle(TPixel32::White);

				FillParameters params;
				params.m_palette = palette.getPointer();
				params.m_styleId = styleId;
				params.m_minFillDepth = 0;
				params.m_maxFillDepth = 15;
				filler.rectFill(newRas->getBounds(), params, false);

				TRasterImageP ri = TRasterImageP(newRas);
				return ri;
			}
		}
	}

	// Error case: return a dummy image (is it really required?)

	TRaster32P ras(10, 10);
	ras->fill(TPixel32(127, 0, 127, 127));

	return TRasterImageP(ras);
}
void FullColorBrushTool::draw()
{
	if (TRasterImageP ri = TRasterImageP(getImage(false))) {
		TRasterP ras = ri->getRaster();

		glColor3d(1.0, 0.0, 0.0);

		tglDrawCircle(m_brushPos, (m_minThick + 1) * 0.5);
		tglDrawCircle(m_brushPos, (m_maxThick + 1) * 0.5);
	}
}
AdjustLevelsUndo::AdjustLevelsUndo(int *in0, int *in1, int *out0, int *out1,
								   int r, int c, TRasterP ras)
	: m_r(r), m_c(c), m_rasSize(ras->getLx() * ras->getLy() * ras->getPixelSize())
{
	memcpy(m_in0, in0, sizeof(m_in0));
	memcpy(m_in1, in1, sizeof(m_in1));
	memcpy(m_out0, out0, sizeof(m_out0));
	memcpy(m_out1, out1, sizeof(m_out1));

	static int counter = 0;
	m_rasId = QString("AdjustLevelsUndo") + QString::number(++counter);

	TImageCache::instance()->add(m_rasId, TRasterImageP(ras));
}
QScriptValue ImageBuilder::fill(const QString &colorName) {
  QColor color;
  QScriptValue err = checkColor(context(), colorName, color);
  if (err.isError()) return err;
  TPixel32 pix(color.red(), color.green(), color.blue(), color.alpha());
  if (m_img) {
    if (m_img->getType() != TImage::RASTER)
      context()->throwError("Can't fill a non-'Raster' image");
    TRaster32P ras = m_img->raster();
    if (ras) ras->fill(pix);
  } else if (m_width > 0 && m_height > 0) {
    TRaster32P ras(m_width, m_height);
    ras->fill(pix);
    m_img = TRasterImageP(ras);
  }
  return context()->thisObject();
}
Esempio n. 10
0
void Writer::write(const TRaster32P &ras, Processor *processor)
{
	m_context->makeCurrent();
	glClear(GL_COLOR_BUFFER_BIT);
	if (ras) {
		glRasterPos2d(0, 0);
		glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // ras->getWrap());
		glDrawPixels(ras->getLx(), ras->getLy(), TGL_FMT, TGL_TYPE, ras->getRawData());
	}
	if (processor) {
		processor->draw();
	}
	glRasterPos2d(0, 0);
	glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); // ras->getWrap());
	glReadPixels(0, 0, m_raster->getLx(), m_raster->getLy(), TGL_FMT, TGL_TYPE, m_raster->getRawData());

	TImageP img = TRasterImageP(m_raster);
	m_levelWriter->getFrameWriter(++m_frameCount)->save(img);
}
Esempio n. 11
0
void PreviewToggleCommand::postProcess() {
  TApp *app                   = TApp::instance();
  CleanupSettingsModel *model = CleanupSettingsModel::instance();

  TXshSimpleLevel *sl;
  TFrameId fid;
  model->getCleanupFrame(sl, fid);

  assert(sl);
  if (!sl) return;

  // Retrieve transformed image
  TRasterImageP transformed;
  {
    TRasterImageP original;
    TAffine transform;

    model->getPreviewData(original, transformed, transform);
    if (!transformed) return;
  }

  // Perform post-processing
  TRasterImageP preview(
      TCleanupper::instance()->processColors(transformed->getRaster()));

  TPointD dpi;
  transformed->getDpi(dpi.x, dpi.y);
  preview->setDpi(dpi.x, dpi.y);

  transformed = TRasterImageP();

  // Substitute current frame image with previewed one
  sl->setFrame(fid, preview);

  TApp::instance()->getCurrentLevel()->notifyLevelChange();
}
	TRasterBrightnessUndo(int brightness, int contrast, int r, int c, TRasterP ras)
		: m_r(r), m_c(c), m_rasId(), m_brightness(brightness), m_contrast(contrast), m_rasSize(ras->getLx() * ras->getLy() * ras->getPixelSize())
	{
		m_rasId = QString("BrightnessUndo") + QString::number((uintptr_t) this);
		TImageCache::instance()->add(m_rasId, TRasterImageP(ras));
	}
Esempio n. 13
0
  bool addFrame(ToonzScene &scene, int row, bool isLast) {
    assert(m_status == 3);
    if (!m_started) start(scene);

    TDimension cameraRes   = scene.getCurrentCamera()->getRes();
    TDimensionD cameraSize = scene.getCurrentCamera()->getSize();

    TPointD center(0.5 * cameraSize.lx, 0.5 * cameraSize.ly);

    double sx = (double)m_offlineGlContext.getLx() / (double)cameraRes.lx;
    double sy = (double)m_offlineGlContext.getLy() / (double)cameraRes.ly;
    double sc = std::min(sx, sy);

    // TAffine cameraAff =
    // scene.getXsheet()->getPlacement(TStageObjectId::CameraId(0), row);
    TAffine cameraAff = scene.getXsheet()->getCameraAff(row);

    double dpiScale =
        (1.0 / Stage::inch) * (double)cameraRes.lx / cameraSize.lx;

    // TAffine viewAff = TScale(dpiScale*sc) * TTranslation(center)*
    // cameraAff.inv();
    TAffine viewAff = TTranslation(0.5 * cameraRes.lx, 0.5 * cameraRes.ly) *
                      TScale(dpiScale * sc) * cameraAff.inv();

    TRect clipRect(m_offlineGlContext.getBounds());
    TPixel32 bgColor = scene.getProperties()->getBgColor();

    m_offlineGlContext.makeCurrent();
    TPixel32 bgClearColor = m_bgColor;

    if (m_alphaEnabled && m_alphaNeeded) {
      const double maxValue = 255.0;
      double alpha          = (double)bgClearColor.m / maxValue;
      bgClearColor.r *= alpha;
      bgClearColor.g *= alpha;
      bgClearColor.b *= alpha;
    }
    m_offlineGlContext.clear(bgClearColor);

    Stage::VisitArgs args;
    args.m_scene = &scene;
    args.m_xsh   = scene.getXsheet();
    args.m_row   = row;
    args.m_col   = m_columnIndex;
    args.m_osm   = &m_osMask;

    ImagePainter::VisualSettings vs;
    Stage::OpenGlPainter painter(viewAff, clipRect, vs, false, true);

    Stage::visit(painter, args);
    /*
painter,
&scene,
scene.getXsheet(), row,
m_columnIndex, m_osMask,
false,0);
*/
    TImageWriterP writer = m_lw->getFrameWriter(m_frameIndex++);
    if (!writer) return false;

#ifdef MACOSX
    glFinish();  // per fissare il bieco baco su Mac/G3
#endif

    TRaster32P raster = m_offlineGlContext.getRaster();

#ifdef MACOSX
    if (m_alphaEnabled && m_alphaNeeded)
      checkAndCorrectPremultipliedImage(raster);
#endif

    if (Preferences::instance()->isSceneNumberingEnabled())
      TRasterImageUtils::addSceneNumbering(TRasterImageP(raster),
                                           m_frameIndex - 1,
                                           scene.getSceneName(), row + 1);
    TRasterImageP img(raster);
    writer->save(img);

    return true;
  }
	TRasterAntialiasUndo(int threshold, int softness, int r, int c, TRasterP ras)
		: m_r(r), m_c(c), m_rasId(), m_threshold(threshold), m_softness(softness), m_rasSize(ras->getLx() * ras->getLy() * ras->getPixelSize())
	{
		m_rasId = QString("AntialiasUndo_") + QString::number(uintptr_t(this));
		TImageCache::instance()->add(m_rasId, TRasterImageP(ras));
	}
Esempio n. 15
0
void Iwa_TiledParticlesFx::doCompute(TTile &tile, double frame, const TRenderSettings &ri)
{
	std::vector<int> lastframe;
	std::vector<TLevelP> partLevel;

	TPointD p_offset;
	TDimension p_size(0, 0);

	/*- 参照画像ポートの取得 -*/
	std::vector<TRasterFxPort *> part_ports;   /*- テクスチャ素材画像のポート -*/
	std::map<int, TRasterFxPort *> ctrl_ports; /*- コントロール画像のポート番号/ポート -*/
	int portsCount = this->getInputPortCount();

	for (int i = 0; i < portsCount; ++i) {
		std::string tmpName = this->getInputPortName(i);
		QString portName = QString::fromStdString(tmpName);

		if (portName.startsWith("T")) {
			TRasterFxPort *tmpPart = (TRasterFxPort *)this->getInputPort(tmpName);
			if (tmpPart->isConnected())
				part_ports.push_back((TRasterFxPort *)this->getInputPort(tmpName));
		} else {
			portName.replace(QString("Control"), QString(""));
			TRasterFxPort *tmpCtrl = (TRasterFxPort *)this->getInputPort(tmpName);
			if (tmpCtrl->isConnected())
				ctrl_ports[portName.toInt()] = (TRasterFxPort *)this->getInputPort(tmpName);
		}
	}

	/*- テクスチャ素材のバウンディングボックスを足し合わせる ←この工程、いらないかも?-*/
	if (!part_ports.empty()) {
		TRectD outTileBBox(tile.m_pos, TDimensionD(tile.getRaster()->getLx(), tile.getRaster()->getLy()));
		TRectD bbox;

		for (unsigned int i = 0; i < (int)part_ports.size(); ++i) {
			const TFxTimeRegion &tr = (*part_ports[i])->getTimeRegion();

			lastframe.push_back(tr.getLastFrame() + 1);
			partLevel.push_back(new TLevel());
			partLevel[i]->setName((*part_ports[i])->getAlias(0, ri));

			// The particles offset must be calculated without considering the affine's translational
			// component
			TRenderSettings riZero(ri);
			riZero.m_affine.a13 = riZero.m_affine.a23 = 0;

			// Calculate the bboxes union
			for (int t = 0; t <= tr.getLastFrame(); ++t) {
				TRectD inputBox;
				(*part_ports[i])->getBBox(t, inputBox, riZero);
				bbox += inputBox;
			}
		}

		if (bbox == TConsts::infiniteRectD)
			bbox *= outTileBBox;

		p_size.lx = (int)bbox.getLx() + 1;
		p_size.ly = (int)bbox.getLy() + 1;
		p_offset = TPointD(0.5 * (bbox.x0 + bbox.x1), 0.5 * (bbox.y0 + bbox.y1));
	} else {
		partLevel.push_back(new TLevel());
		partLevel[0]->setName("particles");
		TDimension vecsize(10, 10);
		TOfflineGL *offlineGlContext = new TOfflineGL(vecsize);
		offlineGlContext->clear(TPixel32(0, 0, 0, 0));

		TStroke *stroke;
		stroke = makeEllipticStroke(0.07, TPointD((vecsize.lx - 1) * .5, (vecsize.ly - 1) * .5), 2.0, 2.0);
		TVectorImageP vectmp = new TVectorImage();

		TPalette *plt = new TPalette();
		vectmp->setPalette(plt);
		vectmp->addStroke(stroke);
		TVectorRenderData rd(AffI, TRect(vecsize), plt, 0, true, true);
		offlineGlContext->makeCurrent();
		offlineGlContext->draw(vectmp, rd);

		partLevel[0]->setFrame(0, TRasterImageP(offlineGlContext->getRaster()->clone()));
		p_size.lx = vecsize.lx + 1;
		p_size.ly = vecsize.ly + 1;
		lastframe.push_back(1);

		delete offlineGlContext;
	}

	Iwa_Particles_Engine myEngine(this, frame);

	// Retrieving the dpi multiplier from the accumulated affine (which is isotropic). That is,
	// the affine will be applied *before* this effect - and we'll multiply geometrical parameters
	// by this dpi mult. in order to compensate.
	float dpi = sqrt(fabs(ri.m_affine.det())) * 100;

	TTile tileIn;
	if (TRaster32P raster32 = tile.getRaster()) {
		TFlash *flash = 0;
		myEngine.render_particles(flash, &tile, part_ports, ri, p_size, p_offset, ctrl_ports, partLevel,
								  1, (int)frame, 1, 0, 0, 0, 0, lastframe, getIdentifier());
	} else if (TRaster64P raster64 = tile.getRaster()) {
		TFlash *flash = 0;
		myEngine.render_particles(flash, &tile, part_ports, ri, p_size, p_offset, ctrl_ports, partLevel,
								  1, (int)frame, 1, 0, 0, 0, 0, lastframe, getIdentifier());
	} else
		throw TException("ParticlesFx: unsupported Pixel Type");
}
/*- render_particles から呼ばれる。粒子の数だけ繰り返し -*/
void Particles_Engine::do_render(
    TFlash *flash, Particle *part, TTile *tile,
    std::vector<TRasterFxPort *> part_ports, std::map<int, TTile *> porttiles,
    const TRenderSettings &ri, TDimension &p_size, TPointD &p_offset,
    int lastframe, std::vector<TLevelP> partLevel,
    struct particles_values &values, double opacity_range, int dist_frame,
    std::map<std::pair<int, int>, double> &partScales) {
  // Retrieve the particle frame - that is, the *column frame* from which we are
  // picking
  // the particle to be rendered.
  int ndx = part->frame % lastframe;

  TRasterP tileRas(tile->getRaster());

  std::string levelid;
  double aim_angle = 0;
  if (values.pathaim_val) {
    double arctan = atan2(part->vy, part->vx);
    aim_angle     = arctan * M_180_PI;
  }

  // Calculate the rotational and scale components we have to apply on the
  // particle
  TRotation rotM(part->angle + aim_angle);
  TScale scaleM(part->scale);
  TAffine M(rotM * scaleM);

  // Particles deal with dpi affines on their own
  TAffine scaleAff(m_parent->handledAffine(ri, m_frame));
  double partScale =
      scaleAff.a11 * partScales[std::pair<int, int>(part->level, ndx)];
  TDimensionD partResolution(0, 0);
  TRenderSettings riNew(ri);

  // Retrieve the bounding box in the standard reference
  TRectD bbox(-5.0, -5.0, 5.0, 5.0), standardRefBBox;
  if (part->level <
          (int)part_ports.size() &&  // Not the default levelless cases
      part_ports[part->level]->isConnected()) {
    TRenderSettings riIdentity(ri);
    riIdentity.m_affine = TAffine();

    (*part_ports[part->level])->getBBox(ndx, bbox, riIdentity);

    // A particle's bbox MUST be finite. Gradients and such which have an
    // infinite bbox
    // are just NOT rendered.

    // NOTE: No fx returns half-planes or similar (ie if any coordinate is
    // either
    // (std::numeric_limits<double>::max)() or its opposite, then the rect IS
    // THE infiniteRectD)
    if (bbox == TConsts::infiniteRectD) return;
  }

  // Now, these are the particle rendering specifications
  bbox            = bbox.enlarge(3);
  standardRefBBox = bbox;
  riNew.m_affine  = TScale(partScale);
  bbox            = riNew.m_affine * bbox;
  /*- 縮小済みのParticleのサイズ -*/
  partResolution = TDimensionD(tceil(bbox.getLx()), tceil(bbox.getLy()));

  if (flash) {
    if (!partLevel[part->level]->frame(ndx)) {
      if (part_ports[0]->isConnected()) {
        TTile auxTile;
        TRaster32P tmp;
        tmp = TRaster32P(p_size);
        (*part_ports[0])
            ->allocateAndCompute(auxTile, p_offset, p_size, tmp, ndx, ri);
        partLevel[part->level]->setFrame(ndx,
                                         TRasterImageP(auxTile.getRaster()));
      }
    }

    flash->pushMatrix();

    const TAffine aff;

    flash->multMatrix(scaleM * aff.place(0, 0, part->x, part->y));

    // if(curr_opacity!=1.0 || part->gencol.fadecol || part->fincol.fadecol ||
    // part->foutcol.fadecol)
    {
      TColorFader cf(TPixel32::Red, .5);
      flash->draw(partLevel[part->level]->frame(ndx), &cf);
    }
    // flash->draw(partLevel->frame(ndx), 0);

    flash->popMatrix();
  } else {
    TRasterP ras;

    std::string alias;
    TRasterImageP rimg;
    if (rimg = partLevel[part->level]->frame(ndx)) {
      ras = rimg->getRaster();
    } else {
      alias = "PART: " + (*part_ports[part->level])->getAlias(ndx, riNew);
      if (rimg = TImageCache::instance()->get(alias, false)) {
        ras = rimg->getRaster();

        // Check that the raster resolution is sufficient for our purposes
        if (ras->getLx() < partResolution.lx ||
            ras->getLy() < partResolution.ly)
          ras = 0;
        else
          partResolution = TDimensionD(ras->getLx(), ras->getLy());
      }
    }

    // We are interested in making the relation between scale and (integer)
    // resolution
    // bijective - since we shall cache by using resolution as a partial
    // identification parameter.
    // Therefore, we find the current bbox Lx and take a unique scale out of it.
    partScale      = partResolution.lx / standardRefBBox.getLx();
    riNew.m_affine = TScale(partScale);
    bbox           = riNew.m_affine * standardRefBBox;

    // If no image was retrieved from the cache (or it was not scaled enough),
    // calculate it
    if (!ras) {
      TTile auxTile;
      (*part_ports[part->level])
          ->allocateAndCompute(auxTile, bbox.getP00(),
                               TDimension(partResolution.lx, partResolution.ly),
                               tile->getRaster(), ndx, riNew);
      ras = auxTile.getRaster();

      // For now, we'll just use 32 bit particles
      TRaster32P rcachepart;
      rcachepart = ras;
      if (!rcachepart) {
        rcachepart = TRaster32P(ras->getSize());
        TRop::convert(rcachepart, ras);
      }
      ras = rcachepart;

      // Finally, cache the particle
      addRenderCache(alias, TRasterImageP(ras));
    }

    if (!ras) return;  // At this point, it should never happen anyway...

    // Deal with particle colors/opacity
    TRaster32P rfinalpart;
    double curr_opacity =
        part->set_Opacity(porttiles, values, opacity_range, dist_frame);
    if (curr_opacity != 1.0 || part->gencol.fadecol || part->fincol.fadecol ||
        part->foutcol.fadecol) {
      /*- 毎フレーム現在位置のピクセル色を参照 -*/
      if (values.pick_color_for_every_frame_val && values.gencol_ctrl_val &&
          (porttiles.find(values.gencol_ctrl_val) != porttiles.end()))
        part->get_image_reference(porttiles[values.gencol_ctrl_val], values,
                                  part->gencol.col);

      rfinalpart = ras->clone();
      part->modify_colors_and_opacity(values, curr_opacity, dist_frame,
                                      rfinalpart);
    } else
      rfinalpart = ras;

    // Now, let's build the particle transform before it is overed on the output
    // tile

    // First, complete the transform by adding the rotational and scale
    // components from
    // Particles parameters
    M = ri.m_affine * M * TScale(1.0 / partScale);

    // Then, retrieve the particle position in current reference.
    TPointD pos(part->x, part->y);
    pos = ri.m_affine * pos;

    // Finally, add the translational component to the particle
    // NOTE: p_offset is added to account for the particle relative position
    // inside its level's bbox
    M = TTranslation(pos - tile->m_pos) * M * TTranslation(bbox.getP00());

    if (TRaster32P myras32 = tile->getRaster())
      TRop::over(tileRas, rfinalpart, M);
    else if (TRaster64P myras64 = tile->getRaster())
      TRop::over(tileRas, rfinalpart, M);
    else
      throw TException("ParticlesFx: unsupported Pixel Type");
  }
}
void Particles_Engine::render_particles(
    TFlash *flash, TTile *tile, std::vector<TRasterFxPort *> part_ports,
    const TRenderSettings &ri, TDimension &p_size, TPointD &p_offset,
    std::map<int, TRasterFxPort *> ctrl_ports, std::vector<TLevelP> partLevel,
    float dpi, int curr_frame, int shrink, double startx, double starty,
    double endx, double endy, std::vector<int> last_frame, unsigned long fxId) {
  int frame, startframe, intpart = 0, level_n = 0;
  struct particles_values values;
  double dpicorr = dpi * 0.01, fractpart = 0, dpicorr_shrinked = 0,
         opacity_range = 0;
  bool random_level    = false;
  level_n              = part_ports.size();

  bool isPrecomputingEnabled = false;
  {
    TRenderer renderer(TRenderer::instance());
    isPrecomputingEnabled =
        (renderer && renderer.isPrecomputingEnabled()) ? true : false;
  }

  memset(&values, 0, sizeof(values));
  /*- 現在のフレームでの各種パラメータを得る -*/
  fill_value_struct(values, m_frame);
  /*- 不透明度の範囲(透明〜不透明を 0〜1 に正規化)-*/
  opacity_range = (values.opacity_val.second - values.opacity_val.first) * 0.01;
  /*- 開始フレーム -*/
  startframe = (int)values.startpos_val;
  if (values.unit_val == ParticlesFx::UNIT_SMALL_INCH)
    dpicorr_shrinked = dpicorr / shrink;
  else
    dpicorr_shrinked = dpi / shrink;

  std::map<std::pair<int, int>, double> partScales;
  curr_frame = curr_frame / values.step_val;

  ParticlesManager *pc = ParticlesManager::instance();

  // Retrieve the last rolled frame
  ParticlesManager::FrameData *particlesData = pc->data(fxId);

  std::list<Particle> myParticles;
  TRandom myRandom;
  values.random_val  = &myRandom;
  myRandom           = m_parent->randseed_val->getValue();
  int totalparticles = 0;

  int pcFrame = particlesData->m_frame;
  if (pcFrame > curr_frame) {
    // Clear stored particlesData
    particlesData->clear();
    pcFrame = particlesData->m_frame;
  } else if (pcFrame >= startframe - 1) {
    myParticles    = particlesData->m_particles;
    myRandom       = particlesData->m_random;
    totalparticles = particlesData->m_totalParticles;
  }
  /*- スタートからカレントフレームまでループ -*/
  for (frame = startframe - 1; frame <= curr_frame; ++frame) {
    int dist_frame = curr_frame - frame;
    /*-
     * ループ内の現在のフレームでのパラメータを取得。スタートが負ならフレーム=0のときの値を格納
     * -*/
    fill_value_struct(values, frame < 0 ? 0 : frame * values.step_val);
    /*- パラメータの正規化 -*/
    normalize_values(values, ri);
    /*- maxnum_valは"birth_rate"のパラメータ -*/
    intpart = (int)values.maxnum_val;
    /*-
     * /birth_rateが小数だったとき、各フレームの小数部分を足しこんだ結果の整数部分をintpartに渡す。
     * -*/
    fractpart = fractpart + values.maxnum_val - intpart;
    if ((int)fractpart) {
      values.maxnum_val += (int)fractpart;
      fractpart = fractpart - (int)fractpart;
    }

    std::map<int, TTile *> porttiles;

    // Perform the roll
    /*- RenderSettingsを複製して現在のフレームの計算用にする -*/
    TRenderSettings riAux(ri);
    riAux.m_affine = TAffine();
    riAux.m_bpp    = 32;

    int r_frame;  // Useful in case of negative roll frames
    if (frame < 0)
      r_frame = 0;
    else
      r_frame = frame;
    /*- 出力画像のバウンディングボックス -*/
    TRectD outTileBBox(tile->m_pos, TDimensionD(tile->getRaster()->getLx(),
                                                tile->getRaster()->getLy()));
    /*- Controlに刺さっている各ポートについて -*/
    for (std::map<int, TRasterFxPort *>::iterator it = ctrl_ports.begin();
         it != ctrl_ports.end(); ++it) {
      TTile *tmp;
      /*- ポートが接続されていて、Fx内で実際に使用されていたら -*/
      if ((it->second)->isConnected() && port_is_used(it->first, values)) {
        TRectD bbox;
        (*(it->second))->getBBox(r_frame, bbox, riAux);
        /*- 素材が存在する場合、portTilesにコントロール画像タイルを格納 -*/
        if (!bbox.isEmpty()) {
          if (bbox == TConsts::infiniteRectD)  // There could be an infinite
                                               // bbox - deal with it
            bbox = ri.m_affine.inv() * outTileBBox;

          if (frame <= pcFrame) {
            // This frame will not actually be rolled. However, it was
            // dryComputed - so, declare the same here.
            (*it->second)->dryCompute(bbox, r_frame, riAux);
          } else {
            tmp = new TTile;

            if (isPrecomputingEnabled)
              (*it->second)
                  ->allocateAndCompute(*tmp, bbox.getP00(),
                                       convert(bbox).getSize(), 0, r_frame,
                                       riAux);
            else {
              std::string alias =
                  "CTRL: " + (*(it->second))->getAlias(r_frame, riAux);
              TRasterImageP rimg = TImageCache::instance()->get(alias, false);

              if (rimg) {
                tmp->m_pos = bbox.getP00();
                tmp->setRaster(rimg->getRaster());
              } else {
                (*it->second)
                    ->allocateAndCompute(*tmp, bbox.getP00(),
                                         convert(bbox).getSize(), 0, r_frame,
                                         riAux);

                addRenderCache(alias, TRasterImageP(tmp->getRaster()));
              }
            }

            porttiles[it->first] = tmp;
          }
        }
      }
    }

    if (frame > pcFrame) {
      // Invoke the actual rolling procedure
      roll_particles(tile, porttiles, riAux, myParticles, values, 0, 0, frame,
                     curr_frame, level_n, &random_level, 1, last_frame,
                     totalparticles);

      // Store the rolled data in the particles manager
      if (!particlesData->m_calculated ||
          particlesData->m_frame + particlesData->m_maxTrail < frame) {
        particlesData->m_frame     = frame;
        particlesData->m_particles = myParticles;
        particlesData->m_random    = myRandom;
        particlesData->buildMaxTrail();
        particlesData->m_calculated     = true;
        particlesData->m_totalParticles = totalparticles;
      }
    }

    // Render the particles if the distance from current frame is a trail
    // multiple
    if (frame >= startframe - 1 &&
        !(dist_frame %
          (values.trailstep_val > 1.0 ? (int)values.trailstep_val : 1))) {
      // Store the maximum particle size before the do_render cycle
      std::list<Particle>::iterator pt;
      for (pt = myParticles.begin(); pt != myParticles.end(); ++pt) {
        Particle &part = *pt;
        int ndx        = part.frame % last_frame[part.level];
        std::pair<int, int> ndxPair(part.level, ndx);

        std::map<std::pair<int, int>, double>::iterator it =
            partScales.find(ndxPair);

        if (it != partScales.end())
          it->second = std::max(part.scale, it->second);
        else
          partScales[ndxPair] = part.scale;
      }

      if (values.toplayer_val == ParticlesFx::TOP_SMALLER ||
          values.toplayer_val == ParticlesFx::TOP_BIGGER)
        myParticles.sort(ComparebySize());

      if (values.toplayer_val == ParticlesFx::TOP_SMALLER) {
        std::list<Particle>::iterator pt;
        for (pt = myParticles.begin(); pt != myParticles.end(); ++pt) {
          Particle &part = *pt;
          if (dist_frame <= part.trail && part.scale && part.lifetime > 0 &&
              part.lifetime <=
                  part.genlifetime)  // This last... shouldn't always be?
          {
            do_render(flash, &part, tile, part_ports, porttiles, ri, p_size,
                      p_offset, last_frame[part.level], partLevel, values,
                      opacity_range, dist_frame, partScales);
          }
        }
      } else {
        std::list<Particle>::reverse_iterator pt;
        for (pt = myParticles.rbegin(); pt != myParticles.rend(); ++pt) {
          Particle &part = *pt;
          if (dist_frame <= part.trail && part.scale && part.lifetime > 0 &&
              part.lifetime <= part.genlifetime)  // Same here..?
          {
            do_render(flash, &part, tile, part_ports, porttiles, ri, p_size,
                      p_offset, last_frame[part.level], partLevel, values,
                      opacity_range, dist_frame, partScales);
          }
        }
      }
    }

    std::map<int, TTile *>::iterator it;
    for (it = porttiles.begin(); it != porttiles.end(); ++it) delete it->second;
  }
}
Esempio n. 18
0
TImageP TImageReaderMovProxy::load() {
  TRaster32P ras(m_lr->getSize());
  m_lr->load(ras, m_frameIndex, TPointI(), 1, 1);
  return TRasterImageP(ras);
}
Esempio n. 19
0
TImageP ImageRasterizer::build(int imFlags, void *extData)
{
	assert(!(imFlags & ~(ImageManager::dontPutInCache | ImageManager::forceRebuild)));

	TDimension d(10, 10);
	TPoint off(0, 0);

	// Fetch image
	assert(extData);
	ImageLoader::BuildExtData *data = (ImageLoader::BuildExtData *)extData;

	const std::string &srcImgId = data->m_sl->getImageId(data->m_fid);

	TImageP img = ImageManager::instance()->getImage(srcImgId, imFlags, extData);
	if (img) {
		TVectorImageP vi = img;
		if (vi) {
			TRectD bbox = vi->getBBox();

			d = TDimension(tceil(bbox.getLx()) + 1, tceil(bbox.getLy()) + 1);
			off = TPoint((int)bbox.x0, (int)bbox.y0);

			TPalette *vpalette = vi->getPalette();
			TVectorRenderData rd(TTranslation(-off.x, -off.y), TRect(TPoint(0, 0), d), vpalette, 0, true, true);

			TGlContext oldContext = tglGetCurrentContext();

			// this is too slow.
			{
				QSurfaceFormat format;
				format.setProfile(QSurfaceFormat::CompatibilityProfile);

				TRaster32P ras(d);

				glPushAttrib(GL_ALL_ATTRIB_BITS);
				glMatrixMode(GL_MODELVIEW), glPushMatrix();
				glMatrixMode(GL_PROJECTION), glPushMatrix();
				{
					std::unique_ptr<QOpenGLFramebufferObject> fb(new QOpenGLFramebufferObject(d.lx, d.ly));

					fb->bind();
					assert(glGetError() == 0);

					glViewport(0, 0, d.lx, d.ly);
					glClearColor(0, 0, 0, 0);
					glClear(GL_COLOR_BUFFER_BIT);

					glMatrixMode(GL_PROJECTION);
					glLoadIdentity();
					gluOrtho2D(0, d.lx, 0, d.ly);

					glMatrixMode(GL_MODELVIEW);
					glLoadIdentity();
					glTranslatef(0.375, 0.375, 0.0);

					assert(glGetError() == 0);
					tglDraw(rd, vi.getPointer());
					assert(glGetError() == 0);

					assert(glGetError() == 0);
					glFlush();
					assert(glGetError() == 0);

					QImage img = fb->toImage().scaled(QSize(d.lx, d.ly), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

					int wrap = ras->getLx() * sizeof(TPixel32);
					uchar *srcPix = img.bits();
					uchar *dstPix = ras->getRawData() + wrap * (d.ly - 1);
					for (int y = 0; y < d.ly; y++) {
						memcpy(dstPix, srcPix, wrap);
						dstPix -= wrap;
						srcPix += wrap;
					}
					fb->release();
				}
				glMatrixMode(GL_MODELVIEW), glPopMatrix();
				glMatrixMode(GL_PROJECTION), glPopMatrix();

				glPopAttrib();

				tglMakeCurrent(oldContext);

				TRasterImageP ri = TRasterImageP(ras);
				ri->setOffset(off + ras->getCenter());

				return ri;
			}
		}
	}

	// Error case: return a dummy image (is it really required?)

	TRaster32P ras(d);
	ras->fill(TPixel32(127, 0, 127, 127));

	return TRasterImageP(ras);
}
QString ImageBuilder::add(const TImageP &img, const TAffine &aff) {
  if (fabs(aff.det()) < 0.001) return "";
  if (m_img && (m_img->getType() != img->getType()))
    return "Image type mismatch";

  if (!m_img && img->getType() != TImage::VECTOR && m_width > 0 &&
      m_height > 0) {
    TRasterP ras = img->raster()->create(m_width, m_height);
    if (img->getType() == TImage::RASTER)
      m_img = TRasterImageP(ras);
    else if (img->getType() == TImage::TOONZ_RASTER) {
      m_img = TToonzImageP(ras, ras->getBounds());
      m_img->setPalette(img->getPalette());
    } else
      return "Bad image type";
  }

  if (!m_img && aff.isIdentity()) {
    m_img = img->cloneImage();
  } else if (img->getType() == TImage::VECTOR) {
    // vector image
    if (!m_img) {
      // transform
      TVectorImageP vi = img->cloneImage();
      vi->transform(aff);
      m_img = vi;
    } else {
      // merge
      TVectorImageP up = img;
      TVectorImageP dn = m_img;
      dn->mergeImage(up, aff);
    }
  } else {
    if (img->getType() != TImage::TOONZ_RASTER &&
        img->getType() != TImage::RASTER) {
      // this should not ever happen
      return "Bad image type";
    }
    TRasterP up = img->raster();
    if (!m_img) {
      // create an empty bg
      TRasterP ras = up->create();
      ras->clear();
      if (img->getType() == TImage::TOONZ_RASTER) {
        TRasterCM32P rasCm = ras;
        m_img              = TToonzImageP(rasCm,
                             TRect(0, 0, ras->getLx() - 1, ras->getLy() - 1));
        m_img->setPalette(img->getPalette());
      } else {
        m_img = TRasterImageP(ras);
      }
    }
    TRasterP dn = m_img->raster();
    if (aff.isTranslation() && aff.a13 == floor(aff.a13) &&
        aff.a23 == floor(aff.a23)) {
      // just a integer coord translation
      TPoint delta = -up->getCenter() + dn->getCenter() +
                     TPoint((int)aff.a13, (int)aff.a23);
      TRop::over(dn, up, delta);
    } else {
      TAffine aff1 = TTranslation(dn->getCenterD()) * aff *
                     TTranslation(-up->getCenterD());
      TRop::over(dn, up, aff1, TRop::Mitchell);
    }
  }
  return "";
}