Exemple #1
0
// Change the aspect ratio of a rectangle.
// The mode can be "area", "width", "height", "fit", "fill" or "stretch".
// Panics if mode is empty or unrecognized.
func SetAspect(w, h, aspect float64, mode string) (float64, float64) {
	switch mode {
	case "area":
		// aspect = width / height
		// width = height * aspect
		// width^2 = width * height * aspect
		// height = width / aspect
		// height^2 = width * height / aspect
		w, h = math.Sqrt(w*h*aspect), math.Sqrt(w*h/aspect)
	case "width":
		// Set height from width.
		h = w / aspect
	case "height":
		// Set width from height.
		w = h * aspect
	case "fit":
		// Shrink one dimension.
		w, h = math.Min(w, h*aspect), math.Min(h, w/aspect)
	case "fill":
		// Grow one dimension.
		w, h = math.Max(w, h*aspect), math.Max(h, w/aspect)
	case "stretch":
		// Do nothing.
	case "":
		panic("no mode specified")
	default:
		panic("unknown mode: " + mode)
	}
	return w, h
}
Exemple #2
0
// AdjustSigmoid changes the contrast of the image using a sigmoidal function and returns the adjusted image.
// It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail.
// The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5.
// The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10).
// If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.
//
// Examples:
//
//	dstImage = imaging.AdjustSigmoid(srcImage, 0.5, 3.0) // increase the contrast
//	dstImage = imaging.AdjustSigmoid(srcImage, 0.5, -3.0) // decrease the contrast
//
func AdjustSigmoid(img image.Image, midpoint, factor float64) *image.NRGBA {
	if factor == 0 {
		return Clone(img)
	}

	lut := make([]uint8, 256)
	a := math.Min(math.Max(midpoint, 0.0), 1.0)
	b := math.Abs(factor)
	sig0 := sigmoid(a, b, 0)
	sig1 := sigmoid(a, b, 1)
	e := 1.0e-6

	if factor > 0 {
		for i := 0; i < 256; i++ {
			x := float64(i) / 255.0
			sigX := sigmoid(a, b, x)
			f := (sigX - sig0) / (sig1 - sig0)
			lut[i] = clamp(f * 255.0)
		}
	} else {
		for i := 0; i < 256; i++ {
			x := float64(i) / 255.0
			arg := math.Min(math.Max((sig1-sig0)*x+sig0, e), 1.0-e)
			f := a - math.Log(1.0/arg-1.0)/b
			lut[i] = clamp(f * 255.0)
		}
	}

	fn := func(c color.NRGBA) color.NRGBA {
		return color.NRGBA{lut[c.R], lut[c.G], lut[c.B], c.A}
	}

	return AdjustFunc(img, fn)
}
Exemple #3
0
func (b *Bounds) ExtendPointZ(pointZ PointZ) *Bounds {
	b.Min.X = math.Min(b.Min.X, pointZ.X)
	b.Min.Y = math.Min(b.Min.Y, pointZ.Y)
	b.Max.X = math.Max(b.Max.X, pointZ.X)
	b.Max.Y = math.Max(b.Max.Y, pointZ.Y)
	return b
}
Exemple #4
0
func distanceRectRect(rect1 Rect, rect2 Rect) float64 {
	var d float64 = 10000

	for _, point := range rect1.MakeCorners() {
		d = math.Min(d, distancePointRect(point, rect2))

		if d < 1 {
			return d
		}
	}
	for _, point := range rect2.MakeCorners() {
		d = math.Min(d, distancePointRect(point, rect1))

		if d < 1 {
			return d
		}
	}

	for _, line := range rect1.MakeLines() {
		d = math.Min(d, distanceLineRect(line, rect2))

		if d < 1 {
			return d
		}
	}

	return d
}
Exemple #5
0
func (v3 *Vector3) Min(v *Vector3) *Vector3 {
	v3.X = math.Min(v3.X, v.X)
	v3.Y = math.Min(v3.Y, v.Y)
	v3.Z = math.Min(v3.Z, v.Z)

	return v3
}
Exemple #6
0
func subtractPSF(psf []float32,
	psfWidth uint64,
	residual []float32,
	residualWidth uint64,
	peakPos uint64, psfPeakPos uint64,
	absPeakVal float32,
	gain float32) {
	var rx = float64(xpos(peakPos, residualWidth))
	var ry = float64(ypos(peakPos, residualWidth))

	var px = float64(xpos(psfPeakPos, psfWidth))
	var py = float64(ypos(psfPeakPos, psfWidth))

	var diffx uint64 = uint64(rx - px)
	var diffy uint64 = uint64(ry - py)

	var startx = math.Max(0, float64(rx-px))
	var starty = math.Max(0, float64(ry-py))

	var stopx = math.Min(float64(residualWidth-1), rx+(float64(psfWidth)-px-1))
	var stopy = math.Min(float64(residualWidth-1), ry+(float64(psfWidth)-py-1))

	factor := gain * absPeakVal
	for y := uint64(starty); y <= uint64(stopy); y++ {
		for x := uint64(startx); x <= uint64(stopx); x++ {
			residual[posToIdx(residualWidth, x, y)] -= factor *
				psf[posToIdx(psfWidth, x-diffx, y-diffy)]
		}
	}
}
Exemple #7
0
func (driver *MesosSchedulerDriver) doReliableRegistration(maxBackoff float64) {
	for {
		if !driver.registerOnce() {
			return
		}
		maxBackoff = math.Min(maxBackoff, registrationRetryIntervalMax)

		// If failover timeout is present, bound the maximum backoff
		// by 1/10th of the failover timeout.
		if driver.failoverTimeout > 0 {
			maxBackoff = math.Min(maxBackoff, driver.failoverTimeout/10.0)
		}

		// Determine the delay for next attempt by picking a random
		// duration between 0 and 'maxBackoff' (jitter).
		delay := time.Duration(maxBackoff * rand.Float64())

		log.V(1).Infof("will retry registration in %v if necessary", delay)

		t := time.NewTimer(delay)
		defer t.Stop()

		select {
		case <-driver.stopCh:
			return
		case <-t.C:
			maxBackoff *= 2
		}
	}
}
Exemple #8
0
func extractImage(image *C.struct__VipsImage, o Options) (*C.struct__VipsImage, error) {
	var err error = nil
	inWidth := int(image.Xsize)
	inHeight := int(image.Ysize)

	switch {
	case o.Crop:
		width := int(math.Min(float64(inWidth), float64(o.Width)))
		height := int(math.Min(float64(inHeight), float64(o.Height)))
		left, top := calculateCrop(inWidth, inHeight, o.Width, o.Height, o.Gravity)
		left, top = int(math.Max(float64(left), 0)), int(math.Max(float64(top), 0))
		image, err = vipsExtract(image, left, top, width, height)
		break
	case o.Embed:
		left, top := (o.Width-inWidth)/2, (o.Height-inHeight)/2
		image, err = vipsEmbed(image, left, top, o.Width, o.Height, o.Extend)
		break
	case o.Top > 0 || o.Left > 0:
		if o.AreaWidth == 0 {
			o.AreaHeight = o.Width
		}
		if o.AreaHeight == 0 {
			o.AreaHeight = o.Height
		}
		if o.AreaWidth == 0 || o.AreaHeight == 0 {
			return nil, errors.New("Extract area width/height params are required")
		}
		image, err = vipsExtract(image, o.Left, o.Top, o.AreaWidth, o.AreaHeight)
		break
	}

	return image, err
}
Exemple #9
0
// startingStepSize implements the algorithm for estimating the starting step
// size as described in:
//  - Hairer, E., Wanner, G., Nørsett, S.: Solving Ordinary Differential
//    Equations I: Nonstiff Problems. Springer Berlin Heidelberg (1993)
func startingStepSize(rhs Function, init, tmp *State, weight Weighting, w []float64, order float64, s *Settings) float64 {
	// Store 1 / (rtol * |Y_i| + atol) into w.
	weight(init.Y, w)
	d0 := s.Norm(init.Y, w)
	d1 := s.Norm(init.YDot, w)

	var h0 float64
	if math.Min(d0, d1) < 1e-5 {
		h0 = 1e-6
	} else {
		// Make the increment of an explicit Euler step small compared to the
		// size of the initial value.
		h0 = 0.01 * d0 / d1
	}

	// Perform one explicit Euler step.
	floats.AddScaledTo(tmp.Y, init.Y, h0, init.YDot)
	// Evaluate the right-hand side f(init.Time+h, tmp.Y).
	rhs(tmp.YDot, init.Time+h0, tmp.Y)
	// Estimate the second derivative of the solution.
	floats.Sub(tmp.YDot, init.YDot)
	d2 := s.Norm(tmp.YDot, w) / h0

	var h1 float64
	if math.Max(d1, d2) < 1e-15 {
		h1 = math.Max(1e-6, 1e-3*h0)
	} else {
		h1 = math.Pow(0.01/math.Max(d1, d2), 1/(order+1))
	}

	return math.Min(100*h0, h1)
}
Exemple #10
0
// generateValidatedLengthExample generates a random size array of examples based on what's given.
func (eg *exampleGenerator) generateValidatedLengthExample() interface{} {
	minlength, maxlength := math.Inf(1), math.Inf(-1)
	for _, v := range eg.a.Validations {
		switch actual := v.(type) {
		case *dslengine.MinLengthValidationDefinition:
			minlength = math.Min(minlength, float64(actual.MinLength))
			maxlength = math.Max(maxlength, float64(actual.MinLength))
		case *dslengine.MaxLengthValidationDefinition:
			minlength = math.Min(minlength, float64(actual.MaxLength))
			maxlength = math.Max(maxlength, float64(actual.MaxLength))
		}
	}
	count := 0
	if math.IsInf(minlength, 1) {
		count = int(maxlength) - (eg.r.Int() % 3)
	} else if math.IsInf(maxlength, -1) {
		count = int(minlength) + (eg.r.Int() % 3)
	} else if minlength < maxlength {
		count = int(minlength) + (eg.r.Int() % int(maxlength-minlength))
	} else if minlength == maxlength {
		count = int(minlength)
	} else {
		panic("Validation: MinLength > MaxLength")
	}
	if !eg.a.Type.IsArray() {
		return eg.r.faker.Characters(count)
	}
	res := make([]interface{}, count)
	for i := 0; i < count; i++ {
		res[i] = eg.a.Type.ToArray().ElemType.GenerateExample(eg.r)
	}
	return res
}
Exemple #11
0
func (self *Population) evaluate() {
	for k := 0; k < self.conf.CrossoversCount; k++ {
		if rand.Float64() < self.conf.CrossoverProb {
			g1 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]
			g2 := self.P[rand.Int31n(int32(math.Min(float64(len(self.P)), float64(self.conf.SelectionCount))))]

			child := g1.Crossover(g2)

			if rand.Float64() < self.conf.MutationProb {
				child.Mutate()
			}
			child.EvalFitness()

			self.P = append(self.P, child)
		}
	}

	self.sort()
	if self.conf.RemoveDuplicates {
		self.removeDuplicates()
	}
	for i := range self.P {
		self.P[i].EvalFitness()
	}
	if len(self.P) > self.conf.PopulationSize {
		self.P = self.P[:self.conf.PopulationSize]
	}
	//	pretty.Println(self.P)
}
Exemple #12
0
// stepMovingObj steps the specified MovingObj and draws its image to its new position onto the LabImg.
func stepMovingObj(m *model.MovingObj) {
	x, y := int(m.Pos.X), int(m.Pos.Y)

	// Only horizontal or vertical movement is allowed!
	if x != m.TargetPos.X {
		dx := math.Min(dt*model.V, math.Abs(float64(m.TargetPos.X)-m.Pos.X))
		if x > m.TargetPos.X {
			dx = -dx
			m.Direction = model.DirLeft
		} else {
			m.Direction = model.DirRight
		}
		m.Pos.X += dx
	} else if y != m.TargetPos.Y {
		dy := math.Min(dt*model.V, math.Abs(float64(m.TargetPos.Y)-m.Pos.Y))
		if y > m.TargetPos.Y {
			dy = -dy
			m.Direction = model.DirUp
		} else {
			m.Direction = model.DirDown
		}
		m.Pos.Y += dy
	}

	// Draw image at new position
	m.DrawImg()
}
func (pm *ProjectileManager) CheckCollision(p pM.Projectiler, dx, dy float64) (bool, gameObjectsBase.Activer) {
	center := p.GetCenter()
	newCenter := geometry.MakePoint(center.X+dx, center.Y+dy)
	rects := make([]*geometry.Rectangle, 0, 100)
	rect2obj := make(map[*geometry.Rectangle]gameObjectsBase.Activer)
	for i := int(math.Min(center.Y, newCenter.Y)); i <= int(math.Max(center.Y, newCenter.Y)); i++ {
		for j := int(math.Min(center.X, newCenter.X)); j <= int(math.Max(center.X, newCenter.X)); j++ {
			if pm.field.IsBlocked(j, i) {
				rects = append(rects, pm.field.GetCellRectangle(j, i))
			} else {
				for _, actor := range pm.field.GetActors(j, i) {
					r := actor.GetRectangle()
					rects = append(rects, &r)
					rect2obj[&r] = actor
				}
			}
		}
	}
	s := geometry.MakeSegment(center.X, center.Y, center.X+dx, center.Y+dy)
	for _, rect := range rects {
		if rect.CrossedBySegment(s) {
			return true, rect2obj[rect]
		}
	}
	return false, nil
}
Exemple #14
0
func GeoCell(lat, lon float64, resolution int) string {
	north := 90.0
	south := -90.0
	east := 180.0
	west := -180.0
	cell := make([]byte, resolution, resolution)

	for i := 0; i < resolution; i++ {
		subcellLonSpan := (east - west) / GEOCELL_GRID_SIZE
		subcellLatSpan := (north - south) / GEOCELL_GRID_SIZE

		x := int(math.Min(GEOCELL_GRID_SIZE*(lon-west)/(east-west), GEOCELL_GRID_SIZE-1))
		y := int(math.Min(GEOCELL_GRID_SIZE*(lat-south)/(north-south), GEOCELL_GRID_SIZE-1))

		pos := (y&2)<<2 | (x&2)<<1 | (y&1)<<1 | (x&1)<<0
		cell[i] = GEOCELL_ALPHABET[pos]

		south += subcellLatSpan * float64(y)
		north = south + subcellLatSpan

		west += subcellLonSpan * float64(x)
		east = west + subcellLonSpan
	}

	return string(cell)
}
Exemple #15
0
// RGBToHSV converts an RGB triple to a HSV triple.
//
// Ported from http://goo.gl/Vg1h9
func RGBToHSV(r, g, b uint8) (h, s, v float64) {
	fR := float64(r) / 255
	fG := float64(g) / 255
	fB := float64(b) / 255
	max := math.Max(math.Max(fR, fG), fB)
	min := math.Min(math.Min(fR, fG), fB)
	d := max - min
	s, v = 0, max
	if max > 0 {
		s = d / max
	}
	if max == min {
		// Achromatic.
		h = 0
	} else {
		// Chromatic.
		switch max {
		case fR:
			h = (fG - fB) / d
			if fG < fB {
				h += 6
			}
		case fG:
			h = (fB-fR)/d + 2
		case fB:
			h = (fR-fG)/d + 4
		}
		h /= 6
	}
	return
}
Exemple #16
0
// Expand returns a bounding box that holds both bounding box and a vector.
func (b BB) Expand(v Vect) BB {
	return BB{
		math.Min(b.l, v.X),
		math.Min(b.b, v.Y),
		math.Max(b.r, v.X),
		math.Max(b.t, v.Y)}
}
Exemple #17
0
func recursive(string1, string2 string) float64 {
	if len(string1) == 0 {
		return float64(len(string2))
	}

	if len(string2) == 0 {
		return float64(len(string1))
	}

	if (len(string2) == 0) && (len(string1) == 0) {
		return 0.0
	}

	mismatch_1 := recursive(string1, string2[0:len(string2)-1]) + 1.0
	mismatch_2 := recursive(string1[0:len(string1)-1], string2) + 1.0

	var cost float64
	if string1[len(string1)-1] == string2[len(string2)-1] {
		cost = 0.0
	} else {
		cost = 1.0
	}
	mismatch_3 := recursive(string1[0:len(string1)-1], string2[0:len(string2)-1]) + cost

	return math.Min(math.Min(mismatch_1, mismatch_2), mismatch_3)
}
Exemple #18
0
// Merge returns a bounding box that holds both bounding boxes.
func (a BB) Merge(b BB) BB {
	return BB{
		math.Min(a.l, b.l),
		math.Min(a.b, b.b),
		math.Max(a.r, b.r),
		math.Max(a.t, b.t)}
}
Exemple #19
0
func (b *Microfacet) G(wo, wi, wh *Vector) float64 {
	NdotWh := AbsCosTheta(wh)
	NdotWo := AbsCosTheta(wo)
	NdotWi := AbsCosTheta(wi)
	WOdotWh := AbsDotVector(wo, wh)
	return math.Min(1.0, math.Min((2.0*NdotWh*NdotWo/WOdotWh), (2.0*NdotWh*NdotWi/WOdotWh)))
}
Exemple #20
0
//uses local absolute path, generates metadata for file
func createFileMeta(path string, f os.FileInfo) (bt bt_file, err error) {
	d, err := ioutil.ReadFile(path)
	if err != nil {
		return bt, err
	}

	fmt.Println(f.Size())
	//TODO compute this smarter, not just min(256k, len(file))
	plength := int(math.Min(float64(PIECE_LENGTH), float64(f.Size())))

	if plength == 0 {
		return bt, err
	}
	iters := len(d) / plength
	if len(d)%plength > 0 {
		iters += 1
	}

	//compute sha1 of each piece
	var wg sync.WaitGroup
	pieces := make([]byte, 0, iters*20)
	wg.Add(iters)
	for i := 0; i < iters; i++ {
		go func(i int) {
			s := sha1.Sum(d[plength*i : int(math.Min(float64(plength*(i+1)), float64(len(d))))])
			pieces = append(pieces[:i*20], append(s[:], pieces[i*20:]...)...)
			wg.Done()
		}(i)
	}
	wg.Wait()
	return bt_file{f.ModTime().Unix(), f.Size(), plength, string(pieces)}, nil
}
Exemple #21
0
func (p *Paginator) Pages() []int {
	if p.pageRange == nil && p.nums > 0 {
		var pages []int
		pageNums := p.PageNums()
		page := p.Page()
		switch {
		case page >= pageNums-4 && pageNums > 9:
			start := pageNums - 9 + 1
			pages = make([]int, 9)
			for i, _ := range pages {
				pages[i] = start + i
			}
		case page >= 5 && pageNums > 9:
			start := page - 5 + 1
			pages = make([]int, int(math.Min(9, float64(page+4+1))))
			for i, _ := range pages {
				pages[i] = start + i
			}
		default:
			pages = make([]int, int(math.Min(9, float64(pageNums))))
			for i, _ := range pages {
				pages[i] = i + 1
			}
		}
		p.pageRange = pages
	}
	return p.pageRange
}
Exemple #22
0
// RGBToHSL converts an RGB triple to a HSL triple.
//
// Ported from http://goo.gl/Vg1h9
func RGBToHSL(r, g, b uint8) (h, s, l float64) {
	fR := float64(r) / 255
	fG := float64(g) / 255
	fB := float64(b) / 255
	max := math.Max(math.Max(fR, fG), fB)
	min := math.Min(math.Min(fR, fG), fB)
	l = (max + min) / 2
	if max == min {
		// Achromatic.
		h, s = 0, 0
	} else {
		// Chromatic.
		d := max - min
		if l > 0.5 {
			s = d / (2.0 - max - min)
		} else {
			s = d / (max + min)
		}
		switch max {
		case fR:
			h = (fG - fB) / d
			if fG < fB {
				h += 6
			}
		case fG:
			h = (fB-fR)/d + 2
		case fB:
			h = (fR-fG)/d + 4
		}
		h /= 6
	}
	return
}
Exemple #23
0
func cellIDFromFaceIJWrap(f, i, j int) CellID {
	// Convert i and j to the coordinates of a leaf cell just beyond the
	// boundary of this face.  This prevents 32-bit overflow in the case
	// of finding the neighbors of a face cell.
	i = clamp(i, -1, maxSize)
	j = clamp(j, -1, maxSize)

	// We want to wrap these coordinates onto the appropriate adjacent face.
	// The easiest way to do this is to convert the (i,j) coordinates to (x,y,z)
	// (which yields a point outside the normal face boundary), and then call
	// xyzToFaceUV to project back onto the correct face.
	//
	// The code below converts (i,j) to (si,ti), and then (si,ti) to (u,v) using
	// the linear projection (u=2*s-1 and v=2*t-1).  (The code further below
	// converts back using the inverse projection, s=0.5*(u+1) and t=0.5*(v+1).
	// Any projection would work here, so we use the simplest.)  We also clamp
	// the (u,v) coordinates so that the point is barely outside the
	// [-1,1]x[-1,1] face rectangle, since otherwise the reprojection step
	// (which divides by the new z coordinate) might change the other
	// coordinates enough so that we end up in the wrong leaf cell.
	const scale = 1.0 / maxSize
	limit := math.Nextafter(1, 2)
	u := math.Max(-limit, math.Min(limit, scale*float64((i<<1)+1-maxSize)))
	v := math.Max(-limit, math.Min(limit, scale*float64((j<<1)+1-maxSize)))

	// Find the leaf cell coordinates on the adjacent face, and convert
	// them to a cell id at the appropriate level.
	f, u, v = xyzToFaceUV(faceUVToXYZ(f, u, v))
	return cellIDFromFaceIJ(f, stToIJ(0.5*(u+1)), stToIJ(0.5*(v+1)))
}
Exemple #24
0
func RectsIntersection(r1, r2 Rect) (ri Rect) {
	ri.Min.X = math.Max(r1.Min.X, r2.Min.X)
	ri.Min.Y = math.Max(r1.Min.Y, r2.Min.Y)
	ri.Max.X = math.Min(r1.Max.X, r2.Max.X)
	ri.Max.Y = math.Min(r1.Max.Y, r2.Max.Y)
	return
}
Exemple #25
0
func (v3 *Vector3) Clamp(min, max *Vector3) *Vector3 {
	v3.X = math.Max(min.X, math.Min(max.X, v3.X))
	v3.Y = math.Max(min.Y, math.Min(max.Y, v3.Y))
	v3.Z = math.Max(min.Z, math.Min(max.Z, v3.Z))

	return v3
}
func (p *Pagination) Pages(maxShowPages int) []int {

	if maxShowPages < 5 || maxShowPages > MAX_SHOW_PAGE {
		maxShowPages = MAX_SHOW_PAGE
	}
	middlePageNum := maxShowPages / 2
	if p.pageRange == nil && p.Total > 0 {
		var pages []int
		pageNums := p.TotalPages()
		page := p.Page
		switch {
		case page >= pageNums-middlePageNum && pageNums > maxShowPages:
			start := pageNums - maxShowPages + 1
			pages = make([]int, maxShowPages)
			for i := range pages {
				pages[i] = start + i
			}
		case page >= (middlePageNum+1) && pageNums > maxShowPages:
			start := page - middlePageNum
			pages = make([]int, int(math.Min(float64(maxShowPages), float64(page+middlePageNum+1))))
			for i := range pages {
				pages[i] = start + i
			}
		default:
			pages = make([]int, int(math.Min(float64(maxShowPages), float64(pageNums))))
			for i := range pages {
				pages[i] = i + 1
			}
		}
		p.pageRange = pages
	}
	return p.pageRange
}
Exemple #27
0
func (b *Bounds) ExtendPoint(point Point) *Bounds {
	b.Min.X = math.Min(b.Min.X, point.X)
	b.Min.Y = math.Min(b.Min.Y, point.Y)
	b.Max.X = math.Max(b.Max.X, point.X)
	b.Max.Y = math.Max(b.Max.Y, point.Y)
	return b
}
Exemple #28
0
// GetStringBounds returns the approximate pixel bounds of the string s at x, y.
// The left edge of the em square of the first character of s
// and the baseline intersect at 0, 0 in the returned coordinates.
// Therefore the top and left coordinates may well be negative.
func (gc *ImageGraphicContext) GetStringBounds(s string) (left, top, right, bottom float64) {
	font, err := gc.loadCurrentFont()
	if err != nil {
		log.Println(err)
		return 0, 0, 0, 0
	}
	top, left, bottom, right = 10e6, 10e6, -10e6, -10e6
	cursor := 0.0
	prev, hasPrev := truetype.Index(0), false
	for _, rune := range s {
		index := font.Index(rune)
		if hasPrev {
			cursor += fUnitsToFloat64(font.Kerning(int32(gc.Current.Scale), prev, index))
		}
		if err := gc.glyphBuf.Load(gc.Current.Font, int32(gc.Current.Scale), index, truetype.NoHinting); err != nil {
			log.Println(err)
			return 0, 0, 0, 0
		}
		e0 := 0
		for _, e1 := range gc.glyphBuf.End {
			ps := gc.glyphBuf.Point[e0:e1]
			for _, p := range ps {
				x, y := pointToF64Point(p)
				top = math.Min(top, y)
				bottom = math.Max(bottom, y)
				left = math.Min(left, x+cursor)
				right = math.Max(right, x+cursor)
			}
		}
		cursor += fUnitsToFloat64(font.HMetric(int32(gc.Current.Scale), index).AdvanceWidth)
		prev, hasPrev = index, true
	}
	return left, top, right, bottom
}
Exemple #29
0
func (b *Bounds) ExtendPointZM(pointZM PointZM) *Bounds {
	b.Min.X = math.Min(b.Min.X, pointZM.X)
	b.Min.Y = math.Min(b.Min.Y, pointZM.Y)
	b.Max.X = math.Max(b.Max.X, pointZM.X)
	b.Max.Y = math.Max(b.Max.Y, pointZM.Y)
	return b
}
Exemple #30
0
// fast nearest-neighbor resize, no filtering
func resizeNearest(src *image.NRGBA, width, height int) *image.NRGBA {
	dstW, dstH := width, height

	srcBounds := src.Bounds()
	srcW := srcBounds.Max.X
	srcH := srcBounds.Max.Y

	dst := image.NewNRGBA(image.Rect(0, 0, dstW, dstH))

	dx := float64(srcW) / float64(dstW)
	dy := float64(srcH) / float64(dstH)

	Parallel(dstH, func(partStart, partEnd int) {

		for dstY := partStart; dstY < partEnd; dstY++ {
			fy := (float64(dstY)+0.5)*dy - 0.5

			for dstX := 0; dstX < dstW; dstX++ {
				fx := (float64(dstX)+0.5)*dx - 0.5

				srcX := int(math.Min(math.Max(math.Floor(fx+0.5), 0.0), float64(srcW)))
				srcY := int(math.Min(math.Max(math.Floor(fy+0.5), 0.0), float64(srcH)))

				srcOff := srcY*src.Stride + srcX*4
				dstOff := dstY*dst.Stride + dstX*4

				copy(dst.Pix[dstOff:dstOff+4], src.Pix[srcOff:srcOff+4])
			}
		}

	})

	return dst
}