add COPYING
[chise/ruby.git] / src / stroke.rb
1 #!/usr/bin/env ruby
2 #
3 # StrokeFont library by eto 2003-0311
4 # Copyright (C) 2002-2003 Kouichirou Eto
5 #     All rights reserved.
6 #     This is free software with ABSOLUTELY NO WARRANTY.
7 #
8 # You can redistribute it and/or modify it under the terms of 
9 # the GNU General Public License version 2.
10 #
11
12 require 'sgl'
13 require 'kage'
14 require 'csf'
15
16 module StrokeFont
17   class StrokesRenderer #======================================================================
18     def initialize
19       @start_time = nil
20       @strokes = nil
21       @hsv = [0, 0, 100]
22       init
23     end
24     attr_accessor :hsv
25     def init() @start_time = Time.now; end
26     def set_strokes(strokes)
27       @strokes = strokes
28       init
29     end
30     def draw
31       return if @strokes.nil?
32       @strokes.strokes.each_with_index {|stroke, index|
33         #draw_delay(stroke, index)
34         draw_alpha(stroke, 100)
35       }
36     end
37     def draw_alpha(stroke, time)
38       px, py = 0, 0
39       span = 0.1
40       time += span*2
41       stroke.points.each {|x, y|
42         a = time / span
43         colorHSV(@hsv[0], @hsv[1], @hsv[2], a*100.0)
44         line(px, py, x, y) if (px != 0 || py != 0) #最初の点ではない
45         px, py = x, y
46         time -= span
47       }
48     end
49     def draw_delay(stroke, index)
50       now = Time.now
51       @start_time = Time.now if @start_time == nil
52       diff = now - @start_time #開始からの秒数がはいる
53       draw_alpha(stroke, diff - index*0.3)
54     end
55   end
56
57   class Stroke #====================================================================== 一本の線
58     def initialize
59       @points = []
60       @length = nil
61     end
62     attr_reader :points
63     def add_point(x, y)
64       @points << [x, y]
65     end
66     def length #未チェック
67       return @length if @length
68       len = 0.0
69       px, py = -1, -1
70       @points.each {|x, y|
71         if px != -1
72           len += Math.sqrt((x-px)*(x-px)+(y-py)*(y-py))
73         end
74         px, py = x, y
75       }
76       @length = len
77       return @length
78     end
79   end
80
81   class Strokes #====================================================================== 複数の線
82     def initialize
83       @strokes = []
84       @px1, @py1, @px2, @py2 = 0, 0, 0, 0
85       @x1, @y1, @x2, @y2 = 0, 0, 0, 0
86       @px, @py = -1, -1
87     end
88     attr_reader :strokes
89     def add_line(x1, y1, x2, y2)
90       if (@px != x1 || @py != y1) #以前の点とつながっていなかったら、
91         @strokes << Stroke.new
92         @strokes.last.add_point(x1, y1)
93       end
94       @strokes.last.add_point(x2, y2)
95       @px, @py = x2, y2
96     end
97   end
98 end
99
100 #----------------------------------------------------------------------end.