Skip to content

Commit

Permalink
Fix magnification
Browse files Browse the repository at this point in the history
  • Loading branch information
li3zhen1 committed Feb 21, 2024
1 parent 4552950 commit b08c89c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
28 changes: 22 additions & 6 deletions Sources/Grape/Views/ForceDirectedGraph+Gesture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,22 @@ extension ForceDirectedGraph {
internal func onMagnifyChange(
_ value: MagnifyGesture.Value
) {
// print(value.magnification)
var oldScale: Double
if let _scale = self.model.lastScaleRecord {
oldScale = _scale
} else {
self.model.lastScaleRecord = self.model.modelTransform.scale
oldScale = self.model.modelTransform.scale
}

let alpha = -self.model.finalTransform.invert(value.startLocation.simd)
let oldScale = self.model.modelTransform.scale

let oldTranslate = self.model.modelTransform.translate
let newScale = clamp(
Darwin.cbrt(value.magnification) * oldScale,
value.magnification * oldScale,
min: Self.minimumScale,
max: Self.maximumScale)

let newTranslate = (oldScale - newScale) * alpha + oldTranslate

let newModelTransform = ViewportTransform(
Expand All @@ -143,11 +151,19 @@ extension ForceDirectedGraph {
internal func onMagnifyEnd(
_ value: MagnifyGesture.Value
) {
var oldScale: Double
if let _scale = self.model.lastScaleRecord {
oldScale = _scale
} else {
self.model.lastScaleRecord = self.model.modelTransform.scale
oldScale = self.model.modelTransform.scale
}

let alpha = -self.model.finalTransform.invert(value.startLocation.simd)
let oldScale = self.model.modelTransform.scale

let oldTranslate = self.model.modelTransform.translate
let newScale = clamp(
Darwin.cbrt(value.magnification) * oldScale,
value.magnification * oldScale,
min: Self.minimumScale,
max: Self.maximumScale
)
Expand All @@ -156,7 +172,7 @@ extension ForceDirectedGraph {
translate: newTranslate,
scale: newScale
)
// print("newModelTransform", newModelTransform)
self.model.lastScaleRecord = nil
self.model.modelTransform = newModelTransform
guard let action = self.model._onGraphMagnified else { return }
action()
Expand Down
5 changes: 5 additions & 0 deletions Sources/Grape/Views/ForceDirectedGraphModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ public final class ForceDirectedGraphModel<Content: GraphContent> {
return draggingNodeID != nil || backgroundDragStart != nil
}

// records the scale right before a magnification gesture starts
@usableFromInline
var lastScaleRecord: Double? = nil


@usableFromInline
let velocityDecay: Double

Expand Down

0 comments on commit b08c89c

Please sign in to comment.