Skip to content

Commit

Permalink
Fixed up API for DampedSpring spring_force_func
Browse files Browse the repository at this point in the history
  • Loading branch information
philomory committed Apr 9, 2010
1 parent b414d92 commit d9fd07d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
28 changes: 20 additions & 8 deletions lib/chipmunk-ffi/constraints/damped_spring.rb
Expand Up @@ -29,22 +29,34 @@ def initialize(a_body, b_body, anchr_one, anchr_two,
@struct = DampedSpringStruct.new(CP.cpDampedSpringNew(
a_body.struct.pointer,b_body.struct.pointer,anchr_one.struct,anchr_two.struct,
rest_length, stiffness, damping))
set_data_pointer
set_initial_force_proc
end


# FIXME: Ideally, we'd prefer to pass DampedSprings, rather than DampedSpringStructs,
# to the user's lambda; or, better still, pass no spring at all, and allow them to refer
# to self. However, this means using wrapper procs in both the getter and the setter; in
# the case where the user takes a lambda recieved from a reader and supplies it to a writer;
# Each time this happens, we get a more deeply nested chain of lambdas.
def spring_force_func
@struct.spring_force_func
@user_level_force_lambda
end

def spring_force_func=(l)
@spring_force_lambda = l # Keep the lambda from being GCed
@user_level_force_lambda = l

# We keep the lambda in an ivar to keep it from being GCed
@spring_force_lambda = Proc.new do |spring_ptr,dist|
spring_struct = DampedSpringStruct.new(spring_ptr)
obj_id = spring_struct.constraint.data.get_long(0)
spring = ObjectSpace._id2ref(obj_id)
l.call(spring,dist)
end
@struct.spring_force_func = @spring_force_lambda
end

private
def set_initial_force_proc
ffi_func = @struct.spring_force_func
@user_level_force_lambda ||= Proc.new do |spring, dist|
ffi_func.call(spring.struct,dist)
end
end
end
end

Expand Down
4 changes: 2 additions & 2 deletions spec/constraint_spec.rb
Expand Up @@ -207,9 +207,9 @@
boda = CP::Body.new 90, 46
bodb = CP::Body.new 9, 6
joint = CP::DampedSpring.new(boda,bodb,ZERO_VEC_2,ZERO_VEC_2,3,4,5)
joint.spring_force_func.call(joint.struct,1.0).should == 8.0
joint.spring_force_func.call(joint,1.0).should == 8.0
joint.spring_force_func = lambda {|spring,float| float + 1.0 }
joint.spring_force_func.call(joint.struct,1.0).should == 2.0
joint.spring_force_func.call(joint,1.0).should == 2.0
end
end

Expand Down

0 comments on commit d9fd07d

Please sign in to comment.